0

I have a created name.txt file which contains name of students. I want to find the position of each name using it in C.

here is my main C code for extracting name.txt .

FILE *fp;
char c;
char name[100];
fp = fopen("name.txt", "r");
    int ct=0;
    while(c != EOF)
    {
        c = fgetc(fp);
      
        int i = 0;
        name[i] = c;
        
        printf("%c",name[i]);
        
    }

And here is the contents name.txt file

1)Liam  
2)Olivia
3)Noah
4)Emma
5)Oliver    
6)Charlotte
7)Elijah    
8)Amelia
9)Bob
10)Roy
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • It isn't clear what you mean by the position of each name. Two issues though, `c` should be an `int` for proper detection of `EOF`, and the loop checks if `EOF` was reached after using potentially incorrect data. You need something like `while ((c = fgetc(fp)) != EOF)`. – Retired Ninja Nov 17 '22 at 10:18
  • To begin with, you never initialize `c` which means it will have an *indeterminate* value (look at it as garbage). So the very first comparison `c != EOF` might not work as you expect. Secondly, and on an issue related to that comparison, the [`fgetc`](https://en.cppreference.com/w/c/io/fgetc) function returns an **`int`**. This is very important for the comparison to the `int` value `EOF`. – Some programmer dude Nov 17 '22 at 10:19
  • And what you really want is perhaps [`fgets`](https://en.cppreference.com/w/c/io/fgets) to read whole lines instead? – Some programmer dude Nov 17 '22 at 10:20

0 Answers0