【问题标题】:C++ primer 5th 1.4.4C++ 入门 5th 1.4.4
【发布时间】:2015-02-03 00:47:57
【问题描述】:

我是C++的初学者,在看《C++ Primer》5th这本书的时候,对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. 输出答案:

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

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

    100 出现 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?

【问题讨论】:

    标签: c++


    【解决方案1】:

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

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

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

    这就是为什么你必须点击两次Ctrl+D:第一次点击就像Enter 键一样。并且只有第二次命中会创建 EOF 条件。

    【讨论】:

      【解决方案2】:

      您提供的程序可能并非如您所显示的那样一次性接受所有输入。

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

      请参阅此问题的已接受答案,了解为什么第一个 Ctrl+D 不会在您的输入流上导致 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/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-01
        • 2020-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-01
        • 1970-01-01
        相关资源
        最近更新 更多