【发布时间】: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;
}
- 输入数字: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。
我在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++