While永远循环
While loops forever
我试图让程序在输入正数以外的东西后提示用户输入有效的输入,但这段代码只是让它永远循环。如何让用户再次输入有效的输入?
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;
}
相关文章:
- 密码登录程序将永远循环并显示不正确的结果
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- curl_slist->next 永远不会为空,因此当循环卡住时
- 暂停功能,它永远循环
- 而循环永远持续(C++)
- C++ 永远循环
- 更好的做法:永远循环线程或连续线程
- 永远循环..未正确清除用户输入
- 因为循环永远存在
- 永远循环的链接列表破坏者
- 永远不会达到 EOF(无限循环)
- 未定义的行为怪癖:在缓冲区外读取导致循环永远不会终止
- 如何使程序永远循环,直到满足 switch 语句中的特定情况
- CIN循环永远不会终止
- 为什么我的 for 循环永远不会结束
- C++ - 简单 - 嵌套,而循环永远不会终止
- 为什么这个 while 循环永远不会计算为 true
- 为什么我的 do while 循环永远不会结束?C++
- c++循环永远运行而不等待输入
- 为什么这个while循环永远不会结束?