我如何阻止它无休止地循环

How do I stop it from looping endlessly

本文关键字:循环 无休止 何阻止      更新时间:2023-10-16

下面是我的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++书并阅读它。

希望这有帮助。