gpt4 book ai didi

C++ 入门第 5 期 1.4.4

转载 作者:行者123 更新时间:2023-11-28 00:19:26 25 4
gpt4 key购买 nike

我是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. 输出答案:

42 occurs 5 times
55 occurs 2 times
62 occurs 1 times

  1. 然后键入 Ctrl+D
  2. 输出剩下的答案

    100 occurs 3 times

我的问题是为什么我要输入第二次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?

最佳答案

在 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 条件。

关于C++ 入门第 5 期 1.4.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28289534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com