如何阻止它无休止地循环

时间:2014-03-31 23:33:42

标签: c++ while-loop

以下是我的while循环代码。当我为cin输入除double之外的任何东西时,循环是无止境的。如何使它“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;

2 个答案:

答案 0 :(得分:1)

cout << "Enter positive number, or 0\n";
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;
    }
}

答案 1 :(得分:0)

假设您仍然遇到问题,您可以解决以下问题:

#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 ++书籍并阅读它。

希望这会有所帮助。