问题
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.
回答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);
}
}
回答2:
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.
来源:https://stackoverflow.com/questions/50239406/first-character-in-txt-file-doesnt-print-in-c