正在退出do while循环=在C中使用scanf的EOF会额外进行3次迭代
我对这个代码有一些问题 我试图通过stdin读取一个.txt,具体来说,我编译的步骤如下:正在退出do while循环=在C中使用scanf的EOF会额外进行3次迭代,c,while-loop,switch-statement,eof,C,While Loop,Switch Statement,Eof,我对这个代码有一些问题 我试图通过stdin读取一个.txt,具体来说,我编译的步骤如下: g++ eda.c -o eda.exe ./eda.exe < eda.txt 前4行现在没有兴趣了,这些行已经用getline指令读取了。所以问题从第五行开始,“增加…” 有了这一行,我希望得到如下输出:print但我得到: 打印! 打印 打印 (与incr相同) 读取incr和print的特定代码部分以以下开头: charmystring[20] 注: 使用fgets()解决 这是最终代码:
g++ eda.c -o eda.exe
./eda.exe < eda.txt
前4行现在没有兴趣了,这些行已经用getline指令读取了。所以问题从第五行开始,“增加…”
有了这一行,我希望得到如下输出:print代码>但我得到:
打印!
打印
打印代码>
(与incr
相同)
读取incr
和print
的特定代码部分以以下开头:
charmystring[20]代码>
注:
使用fgets()解决
这是最终代码:
do {
//sscanf (mystring,"%s",str);
//int res = strncmp(str, "incr", 10);
if(mystring[0] == 'p') casenumber = 1;
else if(mystring[0] == 'i') casenumber = 2;
else if(mystring[0] == 'd' && mystring[1] == 'o') casenumber = 3;
else if(mystring[0] == 'd' && mystring[1] == 'i') casenumber = 4;
else if(mystring[0] == 'd' && mystring[1] == 'e') casenumber = 5;
switch(casenumber)
{
case 1 :
printf("print!\n" );
break;
case 2 :
printf("increase!\n");
break;
case 3 :
printf("dot!\n");
break;
case 4 :
printf("distance!\n");
break;
case 5 :
printf("decr!\n");
break;
default :
printf("casenumber value is: %d\n", casenumber);
break;
}
casenumber = 0;
} while (fgets (mystring , 21 , stdin) != NULL);
您是否尝试打印scanf的结果
scanf不读取一行,它读取一个简单的字符串,因此代码的循环次数将超出预期
其他问题
在循环中每次运行时清除变量
casenumber = 0;
memset(mystring, 0, sizeof(mystring));
并对scanf的结果进行了测试
if ( result == 1 )
printf("sscanf error");
在SO上查看代码是痛苦的。您的do-while应该是while(scanf(“%19s”,mystring)==1){…}
您在获得结果后立即忽略它,然后将mystring[]
视为它实际工作。老实说,您应该通过fgets()
在线处理这些问题,为什么要发布所有与此问题无关的代码?请尽量将其简化为显示问题的最小示例。@WhozCraig我认为您在所有方面都是正确的,fgets()也是一个很好的选项,但如何使用fgets()执行循环?读取fgets()
manual,读取失败时返回NULL
if ( result == 1 )
printf("sscanf error");