如果语句在c ++中变成无限循环,则很奇怪

时间:2018-02-22 22:10:22

标签: c++ if-statement

下面你可以看到一个用于输入强度统计数据的循环,程序工作正常,但如果在输入数字的部分(cin>> RemainingNumber),如果输入任何类型的字符,它会启动无限循环。

int RemainingStats;
int CurrentStats = 20;
do 
{
    //Cycle For Strength
    cout << "Please input a number between 0 and " << CurrentStats << " for strength: " << endl;
    cin >> RemainingStats;
    if (RemainingStats > CurrentStats || RemainingStats < 0)
    {
        cout << "Invalid input please input a number betwen 0 and " << CurrentStats << endl;
    }
    else if (RemainingStats < CurrentStats || RemainingStats > 0)
    {
        strength += RemainingStats;
        cout << "Strength: " << strength << endl;
    }
} while (RemainingStats > CurrentStats || RemainingStats < 0);

它开始不断向您展示这部分代码

{cout << "Please input a number between 0 and " << CurrentStats << " for strength: " << endl;
    cin >> RemainingStats;
    if (RemainingStats > CurrentStats || RemainingStats < 0)
    {
        cout << "Invalid input please input a number betwen 0 and " << CurrentStats << endl;
    }

除了它不允许你通过RemainingStats而只是继续使用if语句这一事实,如果有人可以提供帮助和解释,我将真正为它做好准备。

image of the result when you input the character

我添加了cin.clear()和cin.ignore()但是之后的下一个循环与它只是针对不同的属性是相同的,如果你输入一个字符,它会从do while循环中消失,这是没有意义的while语句是真的

    do
{
    //Cycle For Agility
    cout << "Please input a number between 0 and " << CurrentStats << " for agility: " << endl;
    cin >> RemainingStats;
    if (RemainingStats > CurrentStats || RemainingStats < 0)
    {
        cout << "Invalid input please input a number betwen 0 and " << CurrentStats << endl;
        cin.clear();
        cin.ignore();
    }
    else
    {
        agility += RemainingStats;
        cout << "Agility: " << agility << endl;
        CurrentStats -= RemainingStats;
    }
} while (RemainingStats > CurrentStats || RemainingStats < 0);

如果您输入了一个字符,您将获得此

Image of the console

这是一个do while switch语句之后的代码,它只是将RemainingStats与Response变量一起切换

do
{
    cin >> Response;
    system("cls");
    switch (Response)
    {

及其无限的开关默认结果一遍又一遍,我在cin&gt;&gt;之前使用cin.clear进行修复。响应,但它仍然退出循环,只是广告以前的结果,这是为了强度,但强度工作正常,即使使用字符输入,因为我添加了此更改

    do 
{
    //Cycle For Strength
    cout << "Please input a number between 0 and " << CurrentStats << " for strength: " << endl;
    cin >> RemainingStats;
    if (RemainingStats > CurrentStats || RemainingStats < 0)
    {
        cout << "Invalid input please input a number betwen 0 and " << CurrentStats << endl;
        cin.clear();
        cin.ignore();
    }
    else if (RemainingStats < CurrentStats || RemainingStats > 0)
    {
        strength += RemainingStats;
        cout << "Strength: " << strength << endl;
        CurrentStats -= RemainingStats;
    }
} while (RemainingStats > CurrentStats || RemainingStats < 0);

请帮助我,我根本不明白为什么代码是这样的

1 个答案:

答案 0 :(得分:0)

请参阅std::basic_istream::operator>>

  

如果提取失败(例如,如果输入了预期数字的字母),则值保持不变,并设置failbit。

由于您输入了任何其他字符,因此读取失败。要弥补这一点,您必须中止无效输入的循环,或者读入字符串并自行进行转换。