Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do-while infinite loop with if c++

In this loop the user should enter an int and program checks if it be odd it will go to next parts, but I can't understand why if the user enter a character that's not int, the program is falling in an infinite loop!

int num;
do {
    cout << "PLEASE enter the num: ";
    cin >> num;
    if (num % 2 == 0)
        cout << "Number should be odd!" << endl;
    else
        break;
} while (true);
//...

Cause anyway char/int != 0 and if it be ==0 too it should stop at next cin but it wont stop! I tried ws(cin) too but it didn't help me. Please tell me how I can fix that problem, and why that's happening.

like image 694
Danial Razavi Avatar asked Jan 24 '26 09:01

Danial Razavi


1 Answers

Becasue your program does not check the result of cin >> num;. Since cin >> num; (where num is an integer) will read all available digits, and if the input is not a digit at all [and not a whitespace character, which are skipped over by cin >>], then it keeps repeatedly trying to read the input.

It's not clear from your question exactly what you want to do when the user has entered "askjhrgAERY8IWE" to your program - there are two solutions that come to mind:

Alt 1. Ask again after removing the errant input. This is probably right for this application as it is interactive, but a terrible idea for an automated program that reads its input from a file.

if(!(cin >> num))
{
     cout << "That deoesn't seem to be a number..." << endl;
     cin.clear();
     cin.ignore(10000, '\n');
}

Alt 2. Exit with an error message. This is clearly the right thing when the typical input is a datafile.

 if(!(cin >> num))
 {
      cout << "That deoesn't seem to be a number..." << endl;
      exit(1); 
 }

You should also add code to deal with end of file in this code - for file-input that should be acceptable [unless the file has specific data to mark the end]. For interactive input (where the user is typing directly to the program), end of file may or may not be considered an error - really depends on what happens next.

like image 118
Mats Petersson Avatar answered Jan 26 '26 01:01

Mats Petersson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!