我正在学习C++编写一个程序来计算每个不同值在输入中出现的连续次数。在C++中计数连续的次数?
的代码是
#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;
}
但它不会算上最后一组数字。例如:如果我输入5 5 5 3 3 4 4 4 4,则输出为:
5发生5次。 3发生2次。
最后设定的结果是“4出现4次”。没有出现。
我想知道代码有什么问题。
请帮忙。
谢谢。
hc。
程序似乎此相关的问题至 在[ideone ...]上正常工作(http://ideone.com/zddsRo) – smac89