我如何阻止它无休止地循环
How do I stop it from looping endlessly
下面是我的while循环代码。当我输入除 cin 的双倍以外的任何东西时,循环是无穷无尽的。我该如何使"cout <<"无效!请输入正确的金额。 "只来一次,之后就直接要求CIN。?
int main ()
double pWeekdays7am_7pm;
cout << "n Please enter the amount of electricity (kWh) produced in the following time periods. If no electricity was produced, enter "0"" << endl << endl;
cout << " Monday-Friday (7am-7pm) ";
cin >> pWeekdays7am_7pm;
while (pWeekdays7am_7pm < 0)
{ cout << " Invalid! Please enter the correct amount. " ;
cin >> pWeekdays7am_7pm;
cout << "Enter positive number, or 0n";
cin >> pWeekdays7am_7pm;
if (pWeekdays7am_7pm < 0)
{
cout << " Invalid! Please enter the correct amount. ";
while (pWeekdays7am_7pm < 0)
{
cin.sync(); cin.clear(); // get rid of anything unwanted
cin >> pWeekdays7am_7pm;
}
}
假设您仍然遇到问题,您遇到的问题的解决方案如下:
#include <limits> // require for limits
#include <iostream> // required for I/O functionality
using namespace std; // to avoid using std:: all the time.
int main (int argc, char **argv) {
double pWeekdays7am_7pm;
cout << "n Please enter the amount of electricity (kWh) produced " <<
"in the following time periods. If no electricity was " <<
"produced, enter "0"" << endl << endl;
cout << "tMonday-Friday (7am-7pm) ";
cin >> pWeekdays7am_7pm;
/*
condition to advance, we check for two things
1) if the conversion to *double* failed, hence cin.fail will return *true*
2) if the converted value is within our limits (>= 0)
*/
while (cin.fail() || pWeekdays7am_7pm < 0) {
cout << "tInvalid value! Please enter the correct amount: " ;
/* reset the stream state */
cin.clear();
/* truncate existing contents up to new line character */
cin.ignore(numeric_limits<std::streamsize>::max(), 'n');
cin >> pWeekdays7am_7pm;
}
/* finally return */
return 0;
}
注释应该非常简单,可以解释此代码的作用,但是如果您还有其他问题,请在此处更新,我将尝试回答。我建议选择一些在线资源或一本好的C++书并阅读它。
希望这有帮助。
相关文章:
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 关于 SIGTSTP 错误和无休止的输入
- 宽藤会话更新无休止循环
- 为什么析构函数无休止地调用自己(导致堆栈溢出)?
- 在图像上覆盖文本的程序会产生无休止的字符串错误
- OpenSSL客户端陷入无休止的读取
- 无休止的 do while 循环C++代码
- 循环无休止地做
- 卡死胡同-无休止的循环,没有解决方案
- C++:如果输入不是整数,为什么这段代码会运行一个无休止的循环
- C++无休止的循环瓶颈
- 这无休止地循环是否有明显的原因
- C++ & SDL:SDL 事件无休止地重复
- 静态分析工具,用于检测由于类型提升而导致的无休止循环
- c++:在修改c字符串数组时帮助纠正无休止循环
- std::advanced()导致无休止的循环
- 为什么我的函数无休止地循环
- 在无休止地循环cout时执行,忽略cin
- boost::asio系统的无休止循环:第一次连接后出现9个错误
- 我如何阻止它无休止地循环