txt文件中的第一个字符不能用C打印
我是C的初学者。我正在用c做一个简单的游戏。
我有一个.txt文件存储玩家的分数,如
gse 12 CKY 8
然后我在C中有这个function,该function根据上面的.txt文件输出得分。
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); }
输出如下
1 se 12 2 KY 8
我尝试了很多东西,但我无法理解。 我猜有些东西正在吞噬代码。 是(c=getc(fp)!=EOF)
问题? 我应该操纵指针以解决这个问题吗?
提前致谢。
如果对fgetc
的调用成功,它将把文件位置指示符递增1。
gse ^ file position indicator will be here after the first call fgetc in your example.
要解决此问题,您可以直接将fgets
与一个变量一起使用,而不是使用name
和score
:
while ((fgets(str, NAME_LENGTH, fp) != NULL) { if (n % 2 == 0) { printf("%d ",n / 2 + 1); printf("%s",str); } else { printf("%s", str); } }
尝试ungetc()函数
未读取字符的function称为ungetc,因为它会反转getc的操作。
在你的代码中尝试: –
while((c=getc(fp)!=EOF)){ ungetc (c,fp); // rest of your code }
ungetc函数将字符c
推回到输入流fp
。 因此,来自流的下一个输入将在其他任何内容之前读取c。