zoukankan      html  css  js  c++  java
  • while((ch=getchar()) !=EOF && ch != ' ');语句作用

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

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

    示例:

     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!
    ",name);
    10    printf("Input2:");
    11    scanf("%c", &sex);
    12    if (sex == 'F' || sex == 'M')
    13    {
    14         printf("sex:%c!
    ",sex);
    15    }
    16    else if (sex == ' ')
    17    {
    18         printf("ERROR: A Space!
    ");
    19    }
    20    else
    21    {
    22         printf("ERROR!
    ");
    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!
    ",name);
    10    while((ch=getchar()) !=EOF && ch != '
    ');
    11    printf("Input2:");
    12    scanf("%c", &sex);
    13    if (sex == 'F' || sex == 'M')
    14    {
    15         printf("sex:%c!
    ",sex);
    16    }
    17    else if (sex == ' ')
    18    {
    19         printf("ERROR: A Space!
    ");
    20    }
    21    else
    22    {
    23         printf("ERROR!
    ");
    24    }
    25    
    26    return 0;
    27 }

    输出:

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

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

    参考:

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

  • 相关阅读:
    打印杨辉三角(直角) 练习
    数组 for 练习
    数组排序 (转)
    java如何获取从键盘输入多个数字,并计算平均数 (转)
    Eclipse快捷键 (转) 待续
    输入首字母判断周几(有瑕疵) 练习
    在java中如何用键盘输入一个数,字符,字符串 (转)
    Java中获取键盘输入值的三种方法 (转)
    Java 位运算(移位、位与、或、异或、非) (转)
    3.4 编程式路由
  • 原文地址:https://www.cnblogs.com/xbook-ben/p/13816850.html
Copyright © 2011-2022 走看看