代码不会退出while循环

时间:2017-07-08 03:27:38

标签: c++

尝试创建我的第一个程序预期行为:

1. User inputs an integer (lets say 7) 
2. User continues to input same integer more times (lets say 4 total)
3. User inputs 8 
4. Program then prints ("the count of 7 was 4")
5. User continues to enter 8 (lets say a 8 was entered a total of 11 times)
6. User enters 73
7. Program then prints ("the count of 8 was 11")

在第4步之后,程序卡住了,任何输入都是“7次输入0次”

#include <iostream>

int main(){

    int inputtedvalue = 0;
    int firstvalue = 0;
    int cnt = 0;

    if(std::cin >> firstvalue){
        ++cnt;
        while(std::cin >> inputtedvalue){
            if(inputtedvalue == firstvalue)
                ++cnt;
            else{

                std::cout << "the count of " << firstvalue <<" is " << cnt << std::endl;
                inputtedvalue = firstvalue;
                cnt= 1;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我正在查看你的例子,我相信以下内容可能会让你回到正确的方向。

using namespace std;

int main(){

int inputtedvalue = 0;
int firstvalue = 0;
int cnt = 0;

cout << "Enter Starting value."<< std::endl; 
if (cin >> firstvalue){

    cout << "New count " << firstvalue <<" of " << cnt << endl;
    while(cin >> inputtedvalue)
    {
        if(inputtedvalue != firstvalue)
        {
            cout << "It Doesn't Match" << endl;
            firstvalue = inputtedvalue;
        }
        else
        {
            cout << "It Matches" << endl;

        }
    }
}
相关问题