C ++ primer 5th 1.4.4

时间:2015-02-03 00:47:58

标签: c++

我是C ++的初学者,在阅读“C ++ Primer”第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;
}
  1. 输入数字:42 42 42 42 42 55 55 62 100 100 100
  2. 输入Ctrl+D
  3. 程序自行运行(不等我输入回车)
  4. 输出答案:
  5.   42次出现42次   55次发生2次   62发生1次

    1. 其次输入Ctrl+D
    2. 输出剩下的答案
        

      100次发生3次

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

      我已经在stackoverflow中搜索了,但我没有得到答案。

      Incorrect output. C++ primer 1.4.4

      confused by control flow execution in C++ Primer example

      C++ Primer fifth edtion book (if statement) is this not correct?

2 个答案:

答案 0 :(得分:3)

在Linux中Ctrl+D并非无条件地意味着&#34;文件结束&#34; (EOF)。实际意味着&#34;将当前待处理的输入推送给等待阅读的人#34;。如果输入缓冲区为非空,则命中Ctrl+D 不会在缓冲区末尾创建EOF条件。只有当输入缓冲区为空时才按Ctrl+D,只有这样才会产生EOF条件。 (有关更多技术说明,请参见此处:https://stackoverflow.com/a/1516177/187690

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

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

这就是你必须两次点击Ctrl+D的原因:第一次点击的工作方式与Enter密钥相同。并且只有第二次击中会产生EOF条件。

答案 1 :(得分:0)

您提供的程序可能无法像您所示的那样一次接受所有输入。

它没有提供您期望的输出的原因是由于程序仍然期望输入,因为&gt;&gt;操作的返回值仍然是逻辑真/无错误。 (它被阻止在:while (std::cin >> val))这是因为你没有在最后一个100之后为输入流提供EOF。换句话说,你的第一个Ctrl+D越过{ {1}}。您的第二个if (std::cin >> currVal)超过了Ctrl+D

请参阅此问题的已接受答案,了解为什么第一个while (std::cin >> val)不会在输入流中导致eofbit错误:Why do I have to type ctrl-d twice?底线是Ctrl+D并不一定意味着EOF;它会导致输入流的刷新。


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

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

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