为什么这个程序不循环?

Why this program doesn't go in loop?

本文关键字:循环 程序 为什么      更新时间:2023-10-16

当我给出错误的输入(如字符串"abx")时,它会给我错误消息,但不会返回循环或要求我重试。此示例来自谷歌 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;
}

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

cin.ignore(10000/'n');

cin.ignore(10000,'n');

参见 cin.ignore() 的参考资料