简体   繁体   English

“刷新输入缓冲区”是什么意思?

[英]What does it mean to "flush the input buffer"?

int prompt(const char *output_message, char *input, const int MAX_SIZE)
{
    printf("%s", output_message);

    int i = 0;
    char ch = '\0';

    while (1)
    {
        ch = (char)getchar();

        if (ch == '\n' || ch == EOF)
        {
            break;
        }
        else if (i < (MAX_SIZE - 1))
        {
            input[i++] = ch;
        }
    }

    input[i] = '\0';

    return i;
}

I wrote this function to get an input string input from the user.我写了这个 function 来获取用户输入的输入字符串。 So getchar(), is going through the buffer until it reaches a newline or the end of the file.所以 getchar() 正在遍历缓冲区,直到到达换行符或文件末尾。 My question is does flushing the input buffer mean to move the FILE pointer(or whatever implementation is there) away from the currently written part in the buffer like I'm doing with getchar()?我的问题是刷新输入缓冲区是否意味着将 FILE 指针(或那里的任何实现)从缓冲区中当前写入的部分移开,就像我使用 getchar() 所做的那样? What does it actually mean to "flush the input buffer"? “刷新输入缓冲区”实际上是什么意思?

"Flushing the input buffer" refers to the attempt to discard unwanted characters from the input stream so that they do not perturb later input calls. “刷新输入缓冲区”是指尝试从输入 stream 中丢弃不需要的字符,这样它们就不会干扰以后的输入调用。

In your code, it doesn't look like you'll have this problem, so flushing the input buffer should not be an issue for you.在您的代码中,看起来您不会遇到这个问题,因此刷新输入缓冲区对您来说应该不是问题。

The unwanted input issue typically occurs when you're doing input using scanf .当您使用scanf进行输入时,通常会出现不需要的输入问题。 scanf typically leaves the user's newline on the input buffer, but later calls to getchar or fgets (or even scanf ) can be badly confused by this. scanf通常将用户的换行符留在输入缓冲区中,但稍后对getcharfgets (甚至scanf )的调用可能会因此而严重混淆。

The problem with flushing the input is that there isn't really a good way of doing it.刷新输入的问题在于并没有真正好的方法。 A popular although not recommended technique is to call fflush(stdin) .一种流行但推荐的技术是调用fflush(stdin) That looks like it ought to be just the ticket, but the problem is that it's not well-defined and not guaranteed to work (although some programmers have found that it works well enough for them, on some platforms).看起来它应该只是门票,但问题是它没有明确定义并且不能保证工作(尽管一些程序员发现它在某些平台上对他们来说已经足够好了)。

See this question and this question (maybe also this one ) for much more on this issue.有关此问题的更多信息,请参阅此问题此问题(也可能是问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM