首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++入门第5版1.4.4为什么不能立即输入std::cout

c++入门第5版1.4.4为什么不能立即输入std::cout
EN

Stack Overflow用户
提问于 2016-03-31 20:31:11
回答 2查看 156关注 0票数 1

“c++ primer 5”1.4.4代码示例如下所示

代码语言:javascript
复制
#include <iostream>
int main()
{
    // currVal is the number we're counting; we'll read new values into val
    int currVal = 0, val = 0;
    // read first number and ensure that we have data to process
    if (std::cin >> currVal) {
        int cnt = 1;  // store the count for the current value we're processing
        while (std::cin >> val) { // read the remaining numbers
            if (val == currVal)   // if the values are the same
                ++cnt;            // add 1 to cnt
            else { // otherwise, print the count for the previous value
                std::cout << currVal << " occurs "
                          << cnt << " times" << std::endl;
                currVal = val;    // remember the new value
                cnt = 1;          // reset the counter
            }
        }  // while loop ends here
        // remember to print the count for the last value in the file
        std::cout << currVal <<  " occurs "
                  << cnt << " times" << std::endl;
    } // outermost if statement ends here
    return 0;
}

如果我输入:

11

11

13

13

13

14

我认为它应该像这样执行:

当我输入

11 11

控制台应显示"11发生2次“。

然后我可以继续输入

13 13 13

那么控制台应该会显示“13次出现3次”。

但只有当我输入完所有数字时,控制台才会输出一次结果。为什么?

谢谢你的帮助。

EN

回答 2

Stack Overflow用户

发布于 2016-03-31 20:37:47

来自终端的输入是线路缓冲的。

第一个std::cin >> currVal阻塞,直到输入在标准输入上可用。

只有按下<Enter>键,才会发生这种情况。(直到该<Enter>,您输入的字符仍然驻留在您的终端/命令框的行缓冲区中。您可以使用退格键、编辑键等;只有当您按下<Enter>时,终端/命令框才会真正将这些字符发送到程序的标准输入。)

对于您预期的行为,请尝试在每个数字后按<Enter>

票数 3
EN

Stack Overflow用户

发布于 2016-03-31 20:46:21

示例中的两个std::cin >> currVal都将阻塞标准输入,std::cin表示来自标准输入的值,在这种情况下,您的键盘就是标准输入。

要确认来自键盘的输入,您需要按下Enter键,然后从键盘的buffer中删除值并由您的代码进行处理。

如果你想获得每一次按键的值,你需要使用类似于std::getchar的东西,该函数会像你所期望的那样立即读取缓冲区。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36333595

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档