So I got this question where we are given a data (txt) file. We need to read it into an array, then report the first, fifth, and last entries of that file. Here is the code that I have thus far. It's reading the first, but the other two are wrong. Any help would be appreciated.

#include <stdio.h>

int main(void)
{
    int index ;  
    int N = 0 ;
    double x[100] ;
    FILE * input ; 
    input = fopen("weights.txt", "r") ;
    if (input == NULL)
    {
              printf("failed to open input file\n") ;
              system("PAUSE") ;
              return (0) ;
    }
    while(fscanf(input,"%lf", &x) == 1)
    {
        N++ ; 
                     
    }    
    printf("The first value in the text file is %g\n", x[0]) ;
    printf("The fifth value in the text file is %g\n", x[4]) ;
    printf("The last value is the text file is %g\n", x[N]) ;
    printf("The number of values = %i\n", N) ;
    system("PAUSE") ;
    return (0) ;
}

Recommended Answers

All 3 Replies

#include <stdio.h>

int main(void)
{
      
    int N = 0 ;
    char x[100] ;
	int i=0;
    FILE * input ; 
    input = fopen("weights.txt", "r") ;
    if (input == NULL)
    {
              printf("failed to open input file\n") ;
               return (0) ;
    }
    while(fscanf(input,"%c", &x[i]) !=EOF)
    {
        N++ ; 
		i++;
		
                     
    }    
    printf("The first value in the text file is %c\n", x[0]) ;
    printf("The fifth value in the text file is %c\n", x[4]) ;
    printf("The last value is the text file is %c\n", x[--N]) ;
    printf("The number of values = %d\n", ++N) ;
    
    return (0) ;
}

Check this out .....

That killed my computer for some reason :(

Read the doubles from the file in this way:

while(fscanf(input,"%lf", &x[N]) == 1)

Even the previous code should work. Dunno why it crashed on your system.

Also there's no error proofing in your code. What if there aren't 5 entries in the file? You gotta display a suitable error msg. Something to think about. :P

Also, don't use system("pause") . It creates a lot of unnecessary overhead. If you want to pause the program at the end of execution, just use getchar() or getch() [getch() is non-portable, though. But if you don't mind that you can create a similar effect to system("pause")]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.