用C ++计算连续次数?

时间:2013-10-10 01:08:36

标签: c++ if-statement while-loop

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

最后设定的结果是&#34; 4次发生4次。&#34;不会出现。

我想知道代码有什么问题。

请帮忙。

感谢。

HC。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您的计划是正确的。当条件为假时,你的while循环将退出

while (std::cin >> val)

当您到达文件末尾(EOF)时,流输入将返回false,该文件来自您可以使用Ctrl-D输入的终端。

尝试将您的输入放在一个文件中,您的程序就可以运行。我使用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 >> )