【问题标题】:how to handle the input buffer in c如何在c中处理输入缓冲区
【发布时间】:2012-12-05 18:12:54
【问题描述】:

我是 c 编程新手,我的程序遇到了这个问题
我有一个从输入缓冲区获取字符的循环

while(c = getchar()){
    if(c == '\n') break;
    if(c == '1') Add();
    if(c == '2') getInput(); // this is where the headache starts
    ....
}

这里是 getInput() 函数

void getInput()
{ 
    char ch = getchar();
    if(ch == '1') doSomething();
    ....
}

但是当从 getInput() 函数调用 getchar() 时,它只获取上次调用 getchar() 后留在输入缓冲区中的字符。我想要它做的是获取新输入的字符。

我已经在谷歌上搜索了两个小时,以寻找一种清除输入缓冲区的好方法,但没有任何帮助。因此,非常感谢您提供指向教程或文章或其他内容的链接,如果有其他方法可以实现,请告诉我。

【问题讨论】:

    标签: c getchar input-buffer


    【解决方案1】:

    首先在这段代码的if条件中会有==比较运算符而不是=赋值运算符。

    while(c = getchar()){
        if(c = '\n') break;
        if(c = '1') Add();
        if(c = '2') getInput(); // this is where the headache starts
        ....
    }
    

    为了停止接受输入,请尝试EOF,可以通过 prssing CTRL+D 给出键盘输入。

    编辑:问题在于\n,当您按下键盘上的ENTER 键时,它实际上被视为输入。所以只改变一行代码。

    if (c ==\n) break;if (c == EOF ) break;,正如我所说,EOF 是输入的结束。

    那么你的代码就可以正常工作了。

    代码流程:

    step 1: suppose `2` is input 
    step 2: getInput() is called
    step 3: suppose `1` as input  // in getInput
    step 4: doSomething() is called  // from getInput
    step 5: After completion of doSomething again come back to while loop , 
    
    but in your case you have already given `\n` character as an input 
    
    when you pressed `1` and `ENTER`.And thus loop terminates.
    

    但是按照我所说的更改代码之后,这应该可以工作。

    注意:为了理解代码流和调试目的,最好将printf() 放在函数的不同位置,并查看输出中哪些行正在执行,哪些行没有执行。

    【讨论】:

    • 我试过了,但它不起作用,因为在第 1 步和第 3 步之间必须刷新输入缓冲区。但这里它没有被刷新,第一次调用 getchar() 的输入缓冲区会影响 getInput() 中的比较
    • 您是否也在Add() 函数中输入,如果是,那么可能是由于那个问题(您还没有向我们展示添加的代码)?否则代码在我的系统上运行良好。
    • 我没有在 add() 中输入(实际上我只是在调用 printf),我已经将代码更改为你所说的,如果你想要我可以发布代码,但它的评论不是很好而且太长了
    【解决方案2】:

    这应该可以工作:(清除输入缓冲区的示例)

    #include <stdio.h> 
    
    int main(void)
    {
      int   ch;
      char  buf[BUFSIZ];
    
      puts("Flushing input");
    
      while ((ch = getchar()) != '\n' && ch != EOF);
    
      printf ("Enter some text: ");
    
      if (fgets(buf, sizeof(buf), stdin))
      {
        printf ("You entered: %s", buf);
      }
    
      return 0;
    }
    
    /*
     * Program output:
     *
     Flushing input
     blah blah blah blah
     Enter some text: hello there
     You entered: hello there
     *
     */
    

    【讨论】:

    • 感谢您的回答,但正如您在代码中看到的那样,我试图获取一个描述选择而不是整个字符串的字符。所以我想要的只是让字符与另一个字符进行比较,然后忘记输入流中剩下的内容,然后调用另一个 getchar()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多