#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 occurs 5 times
55 occurs 2 times
62 occurs 1 times
100 occurs 3 times
但实际输出是:
42 occurs 5 times
有人可以指出我犯了什么错误吗?
答案 0 :(得分:1)
我在Windows系统上运行它并在命令提示符下输入你的输入,它给了我以下输出:
42 occurs 5 times
55 occurs 2 times
62 occurs 1 times
这里的问题是你仍处于while循环中,所以你的最后一个std:cout语句还没有执行。如果您在程序的命令提示符下键入输入并按Enter键,那么您将继续循环,直到std:cin返回false。您可以通过在输出后输入更多数字到程序中来验证这一点,然后再次按ENTER。你将继续循环,直到std:cin返回false,如果你在输入的末尾添加一个数字以外的东西,它将会这样做。