0

I am a beginner in C. I am making a simple game in c.

I have a .txt file that stores players' score such as

gse
12
CKY
8

Then I have this function in C and the function prints out score based on .txt file above.

int n = 0;
int c;
int p=0;
char name[NAME_LENGTH] = { 0 };
char score[NAME_LENGTH] = { 0 };
FILE *fp = fopen("scoreBoard.txt", "r");

if (fp == NULL) {
    printf("no score available\n");
    fflush(stdin);
    getchar();
    return;
}

system("cls");//clears the screen

if (fp){
    while((c=getc(fp)!=EOF)){

        if(n%2==0){
            fgets(name,NAME_LENGTH,fp);
            printf("%d ",n/2+1); //index
            printf("%s",name);
            n++;
        }
        if(n%2==1){
            fgets(score,NAME_LENGTH,fp);
            printf("%s",score);
            n++;
        }
    }

    fclose(fp);
}

printf("=======SCORE=======\n");

printf("Enter AnyKeys");
Sleep(100);
getchar();
getchar();
//fflush(stdin);
}

output is the following

1 se
12
2 KY
8

I tried many things but I can't figure it out. I guess something is eating up the code. Is (c=getc(fp)!=EOF) the problem? Should I manipulate pointer in order to fix this?

Thanks in advance.

Py11
  • 159
  • 1
  • 2
  • 8
  • 1
    Change `while((c=getc(fp)!=EOF))` to `while(fgets(buffer, sizeof buffer, fp) != NULL) { ... } ` and remove the `fgets` in the loop, edit accordingly. The `getc` is interfering, this is why the first character is missing. – Weather Vane May 08 '18 at 17:46
  • **I used this advice in my code** and it worked! – Py11 May 08 '18 at 19:20

2 Answers2

1

If the call to fgetc succeed, it will increment the file position indicator by one.

gse
 ^
 file position indicator will be here after the first call fgetc in
 your example.

To fix that, you can use fgets directly with one variable instead of name and score:

while ((fgets(str, NAME_LENGTH, fp) != NULL) {
    if (n % 2 == 0) {
        printf("%d ",n / 2 + 1);
        printf("%s",str);
    } else {
        printf("%s", str);
    }
}
medalib
  • 937
  • 1
  • 6
  • 7
0

Try ungetc() function

The function to unread a character is called ungetc, because it reverses the action of getc.

In your code try:-

while((c=getc(fp)!=EOF)){
     ungetc (c,fp);
     // rest of your code

}

The ungetc function pushes back the character c onto the input stream fp. So the next input from stream will read c before anything else.

anoopknr
  • 3,177
  • 2
  • 23
  • 33