简体   繁体   中英

How to validate user input a number and the number greater than 0

I'm trying to validate user input that user must enter number and it must be greater than 0, the validation of only numbers I got it working; however, I can't seem to incorporate the validation of greater than 0

float income;
cout << "How much did you earn last year: ";

    //validating imput for income
    while(!(cin >> income))
    {
         char ch;
         cin.clear();
         cout << "Sorry, number must be biger than \"0\" \n"
              << "How much did you make last year: ";
         while(cin.get(ch) && ch != '\n');
    }

Just add the condition to the while , and handle it in the loop:

while ( !(cin >> income) || income < 0.0 ) {
    if ( !cin )
        //  Clean up input stream...
    else
        //  Must be negative number... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM