如果输入非整数,如何防止无限循环?

How to prevent an infinite loop, if a non-integer is entered?

我正在用 C++ turbo(windows 的最新版本)编写赌场游戏。 因此,在该程序的一个特定片段中,要求用户输入严格介于 0 美元和 100000 美元之间的初始金额。

我创建了一个带有嵌入式 if 语句的 do-while 循环:

do{
    cout << "\n\nEnter a deposit amount (between [=10=] and 0000) to play game : $";
    cin >> amount;
    if(amount<=0||amount>=100000)
        cout<<"Please re-enter your amount";
}while(amount<=0||amount>=100000);

当用户(即我)输入字符或小数时出现问题;然后程序失去控制并无限循环。

问题:如果输入的不是整数,我该如何表述要求用户重新输入金额的 if 语句?以后怎么才能不让程序失控呢?

问题是,当您调用 cin >> amount 并且输入是 而不是 数字时,数据会留在缓冲区中。一旦您的代码循环回到相同的操作,您的读取将再次失败,陷入无限循环。

要解决此问题,您需要检查 cin >> amount 的结果,如下所示:

if (cin >> amount) {
    ... // do something with amount
} else {
    cin.clear(); // unset failbit
    // Ignore some input before continuing
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

ignore 函数的引用是 here

您必须清除错误标志并忽略这些字符。

有关 cin.clear() 的示例,请参阅 here

do {
    cout << "Enter a deposit amount (between [=10=] and 0000) to play game : $";
    cin >> amount;

    if(amount<=0 || amount>=100000) {
        cout << "\nPlease re-enter your amount\n";
        cin.clear();
        cin.ignore(10000,'\n');
    }
} while(amount<=0 || amount>=100000);

试试这个

    if(amount<=0||amount>=100000)
    {
        cout<<"Please re-enter your amount";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }