While永远循环

While loops forever

本文关键字:循环 永远 While      更新时间:2023-10-16

我试图让程序在输入正数以外的东西后提示用户输入有效的输入,但这段代码只是让它永远循环。如何让用户再次输入有效的输入?

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 ...

添加标题<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语句,因为我看不到它的用途(除非您有使用它的特定原因)

在while循环中接受输入(我假设其他事情和您的逻辑是正确的):

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