为什么这个程序没有循环?

时间:2017-01-26 19:23:15

标签: c++ do-while cin

当我输入错误的输入时,如字符串“abx”,它会给我错误信息,但不会回到循环中或让我再试一次。此示例来自Google c ++课程示例4。

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

int main()
{
    int isecret, iguess, chance;
    srand(time(NULL));
    isecret = rand() %100 + 1;
    cout<<"Enter integers between 1 to 100"<<endl;
    //cout<<isecret<<endl;
    chance = 0;  

    do{
        if (!(cin>>iguess))
        {
            cout<<"please enter integers between 1 to 100"<<endl;
            cin.clear();
            cin.ignore(10000/'\n');
        }

        else
        {

            if (isecret>iguess)
            {
                cout<<"Your guess is less than the secret"<<endl;
            }
            else if (isecret<iguess)
            {
                cout<<"Your guess is more than the secret"<<endl;
            };
        chance = chance + 1;
        } 
    }
    while(iguess!=isecret);
    cout<<"Congratulation you guess the correct number: "<<isecret<<" in "<<chance<<" chances"<<endl;
    return 0;
}

1 个答案:

答案 0 :(得分:0)

你错过了一个逗号。所以,替换

cin.ignore(10000/'\n');

cin.ignore(10000,'\n');

参见cin.ignore()

的参考资料