而循环永远

时间:2015-03-25 05:38:10

标签: c++

我尝试让程序在输入除正数之外的其他内容时提示用户输入有效输入,但这段代码只是让它永远循环。如何让用户再次输入有效输入?

cout << "\tAmount on deposit: ";
cin >> deposit;
if (!deposit || deposit < 0){

    while (!deposit || deposit < 0)
    {
        cout << "\tPlease enter a positive number! " << endl;
        cout << setw(60) << "Amount on deposit: ";
        cin.ignore(deposit);
    }
}else ...

2 个答案:

答案 0 :(得分:1)

添加标题<limits>并使用此代码删除您在评论中询问的那些字符输入。

将您的代码更改为

while ( deposit <= 0)
{                 
    cin.clear();
    cin.ignore(numeric_limits<int>::max( ),'\n');
    cout << "\tPlease enter a positive number! " << endl;
    cout << setw(60) << "Amount on deposit: ";
    cin >> deposit; // take the input inside the while loop                    
}

问题是您没有更改循环内deposit的值。在你的代码中,deposit的值在你的while循环中不会改变,这会导致无限循环。

此外,您可以将条件更改为

,而不是!deposit
while ( deposit <= 0)

另外,除非你真的需要它,否则我也会删除if语句,因为我没有看到它的使用(除非你有一些特定的理由使用它)

答案 1 :(得分:0)

在while循环中获取输入(我假设其他事情并且你的逻辑是正确的):

while ( deposit < 1)
{
    cout << "\tPlease enter a positive number! " << endl;
    cout << setw(60) << "Amount on deposit: ";
    cin.ignore(deposit);
    cin >> deposit;
}