2013-10-10 69 views
1

我正在学习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。

+0

程序似乎此相关的问题至 在[ideone ...]上正常工作(http://ideone.com/zddsRo) – smac89

回答

0

您的程序是正确的。当条件为假

while (std::cin >> val) 

,当你达到文件(EOF),它从一个终端就可以使用Ctrl-d输入端的流输入将返回false while循环将退出。

尝试将您的输入放在一个文件中,并且您的程序将工作。我已使用cat命令从终端的标准输入复制并将其重定向到名为input的文件。您需要按Ctrd-D来告诉cat您已完成。您也可以使用您最喜爱的编辑器创建input文件。

$ cat > input 
5 5 5 3 3 4 4 4 4 
<press Ctrl-D here> 

现在调用程序并从文件重定向输入

$ ./test < input 

输出是

5 occurs 3 times 
3 occurs 2 times 
4 occurs 4 times 

参见SO

the question on while (cin >>)

0

您似乎只在(val == currVal)为false时才会生成输出。是什么让你认为这会发生在从输入中读取最后4个之后?