c/c++语言开发共享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 availablen"); 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与一个变量一起使用,而不是使用namescore

     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。

      以上就是c/c++开发分享txt文件中的第一个字符不能用C打印相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522545.html

      (0)
      上一篇 2020年12月10日
      下一篇 2020年12月10日

      精彩推荐