我正在阅读 C++ Primer(第五版)。在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
它打印
42 出现 5 次
55 出现 2 次
62 出现 1 次
然而,为了得到最终的输出行
100 出现 3 次
您必须按 CTRL+D。然后打印出来并且程序退出。
为什么是这样?对我来说,看起来应该打印最后一行,并且程序与其他行一起退出。我似乎误解了控制流是如何执行的,所以有人可以澄清一下吗?
ps我知道这一点输出不正确。 C++ 入门 1.4.4 https://stackoverflow.com/questions/20601122/incorrect-output-c-primer-1-4-4 and C++ Primer第五版书(if语句)这不正确吗? https://stackoverflow.com/questions/15188304/c-primer-fifth-edtion-book-if-statement-is-this-not-correct但是,这些都没有解释为什么必须按 ctrl+d 才能打印最终语句。
那是因为这一部分:
while (std::cin >> val)
为了终止读取输入流,您必须使用由 Ctrl-D 提供的 EOF 来终止它。
想一想:cin
默认情况下会跳过空格,每次输入数字时都会用空格(空格、制表符或换行符)分隔它。
程序将如何终止输入? 答案是当它读取 EOF 字符时 - 如前所述,该字符由 Ctrl-D 提供。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)