C++引物第五版 1.4.4.
C++ primer 5th 1.4.4
我是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
- 42 42 55 55 62 100 100 100
- 类型
Ctrl+D
- 程序自行运行(不等我输入回车)
- 输出答案:
42 出现 5 次
55 出现 2 次
62 出现 1 次
- 其次是
Ctrl+D
型 - 输出剩余的答案
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/
- C++初级读本5版1.23从文件流中读取
- 旧版c++中结构和类之间的差异
- C++入门 5 版:类消息和文件夹
- 在链链表中手动插入第五个元素
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 代码精简版页面变为空白
- 具有完整五法则的简单链表
- 编写一个读取五个整数并执行一些任务的C++程序
- VS 2017 社区收到链接器错误,但专业版没有
- 如何使用 ndk 加载 Android 版 AAudio API
- 在 c++ 中使用发行版
- 确定C++应用程序是否作为具有旧版支持的 UWP 应用运行
- C++BST课程的五条规则
- 数组中所有元素的最新最小元素的第五个位置
- 使用模板参数化映射旧版 C 接口的接口中的类型
- C++初级读本第五版字符串练习,要求两段不同的代码提供相同的输出
- C++引物第五版 1.4.4.
- 关于C++初级读本第五版中指针的一些问题
- 顺序容器||C++初级读本第五版练习9.22
- 理解Moothy第2.21节发布的C++初级读本第五版解决方案