while((ch=getchar()) !=EOF && ch != '\n');语句作用

while((ch=getchar()) !=EOF && ch != '\n');语句作用:清除输入缓存。

  如:需要使用函数scanf读取数字123,实际输入的的数据为:123\n(回车),而scanf函数只是读取数字123,\n(回车)还放在输入缓冲内,后续读取数据就可能出错。

示例:

 1 int main(void)
 2 {
 3    char name[20] = {0};
 4    char sex = 0;
 5    int ch = 0;
 6 
 7    printf("Input:");
 8    scanf("%s", &name);
 9    printf("name:%s!\n",name);
10    printf("Input2:");
11    scanf("%c", &sex);
12    if (sex == 'F' || sex == 'M')
13    {
14         printf("sex:%c!\n",sex);
15    }
16    else if (sex == ' ')
17    {
18         printf("ERROR: A Space!\n");
19    }
20    else
21    {
22         printf("ERROR!\n");
23    }
24    
25    return 0;
26 }

输出:

   由于Li与Ming之间存在的空格,第一个scanf获取的输入为Li,而后面的数据都在输入缓存中,第二个scanf会直接从输入缓存中读取一个字符输入,即第一次输入的空格,因此只输入一次回车以后就会输出如上信息。

改进版:

 1 int main(void)
 2 {
 3    char name[20] = {0};
 4    char sex = 0;
 5    int ch = 0;
 6 
 7    printf("Input:");
 8    scanf("%s", &name);
 9    printf("name:%s!\n",name);
10    while((ch=getchar()) !=EOF && ch != '\n');
11    printf("Input2:");
12    scanf("%c", &sex);
13    if (sex == 'F' || sex == 'M')
14    {
15         printf("sex:%c!\n",sex);
16    }
17    else if (sex == ' ')
18    {
19         printf("ERROR: A Space!\n");
20    }
21    else
22    {
23         printf("ERROR!\n");
24    }
25    
26    return 0;
27 }

输出:

  很明显消除了第二个输入读取字符错误问题。

注意:要使用while((ch=getchar()) !=EOF && ch != '\n');形式,不要使用while(ch=getchar() !=EOF && ch != '\n');形式,我在测试的时候少了括号,导致第一次输入完成以后,必须输入EOF(windows下使用组合键Ctrl+Z),然后回车才能继续第二个输入。没带括号形式测试结果:

参考:

https://bbs.csdn.net/topics/320130933

 

posted @ 2020-10-14 20:24  xbook_ben  阅读(2099)  评论(0编辑  收藏  举报