C++引物第五版 1.4.4.

C++ primer 5th 1.4.4

本文关键字:五版 C++      更新时间:2023-10-16

我是C++的初学者,在阅读《C++入门》第5本书时,我对1.4.4章有点困惑。当我在1.4.4中运行该程序时,这是我计算机中的步骤:

#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;
}
    输入数字:42 42 42
  1. 42 42 55 55 62 100 100 100
  2. 类型 Ctrl+D
  3. 程序自行运行(不等我输入回车)
  4. 输出答案:

42 出现 5 次
55 出现 2 次
62 出现 1 次

  1. 其次是Ctrl+D
  2. 输出剩余的答案

    100 出现 3 次

我的问题是为什么我必须输入第二次 Ctrl+D,我的代码环境是 Ubuntu+GCC,我也在 VS2013 中运行它,它只需要输入一次 Ctrl+D。

我在堆栈溢出中搜索过,但没有得到答案。

输出不正确。C++底漆 1.4.4

对C++入门示例中的控制流执行感到困惑

C++ 入门第五版书(如果陈述)这是不正确的吗?

在 Linux 中,Ctrl+D 并不无条件地表示"文件结束"(EOF)。它的实际含义是"将当前挂起的输入推送给正在等待阅读它的人"。如果输入缓冲区为非空,则按Ctrl+D不会在缓冲区末尾创建 EOF 条件。只有当您在输入缓冲区为空时点击Ctrl+D,它才会产生 EOF 条件。(有关更多技术说明,请参见此处:https://stackoverflow.com/a/1516177/187690)

在您的情况下,您将数据作为一行输入,然后在最后点击Ctrl+D。这会将您的输入推送到程序中,并使程序读取和处理数据。但它不会在输入结束时产生 EOF 条件。

因此,一旦循环读取了所有输入数据,程序就不会将其视为 EOF。循环不断等待空输入缓冲区以获取其他数据。如果此时再次按 Ctrl+D,它将被识别为 EOF,您的程序将退出循环并打印最后一行。

这就是为什么你必须Ctrl+D两次:第一次击Enter几乎就像键一样。只有第二次命中才会产生 EOF 条件。

您提供的程序可能不是为了像您所示的那样一次接受所有输入。

它不提供您期望的输出的原因是程序仍然需要输入,因为>>操作的返回值在逻辑上仍然是正确的/无错误的。(它被阻止在:while (std::cin >> val))之所以如此,是因为您在最后 100 个之后没有向输入流提供 EOF。换句话说,你的第一Ctrl+D通过了if (std::cin >> currVal)。你的第二个Ctrl+D通过了while (std::cin >> val)

请参阅此问题的已接受答案,了解为什么第一个Ctrl+D不会导致输入流上的 eofbit 错误:为什么我必须键入 ctrl-d 两次?最重要的是,Ctrl+D并不一定意味着EOF;它会导致输入流刷新。


一次输入一个数字将提供您期望的输出。

或者,您可以提供:42 42 42 42 55 55 62 100 100 100。

http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/