程序出错求解答

zedd3337502212 2020-04-28 02:52:40

程序哪里出错了?求解答
...全文
95 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2020-04-28
  • 打赏
  • 举报
回复
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
fp=fopen("p1.txt","r");
if(fp==NULL)
{
printf("文件打开失败,程序退出! ");
exit( 0);
}
char ch;
int i=0,j=0;

while(!feof(fp))
{
fscanf(fp,"%c",&ch);
if(ch=='[')
i++;
if(ch==']')
j++;
ch = 0; //重置,防止fscanf读取失败后ch保留上一次的值。
}
if(i==j)
printf("0K!\n");
if(i!=j)
printf("ERROR!\n");
}

供参考~
山海皆可平q 2020-04-28
  • 打赏
  • 举报
回复
你只使用feof判断结束是不行的

下面是正确的代码
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp;
fp=fopen("p1.txt","r");
if(fp==NULL)
{
printf("文件打开失败,程序退出! ");
exit( 0);
}
char ch; int i=0,j=0;
while(!feof(fp))
{
int end=fscanf(fp,"%c",&ch);
if(end==-1) break;
if(ch=='[')i++;
if(ch==']')j++;
}
if(i==j)
printf("0K!\n");
if(i!=j)
printf("ERROR!\n");
}


具体错误原因你可以看看这篇文章
https://blog.csdn.net/qq_45721778/article/details/105818272

70,024

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧