Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop with cin when typing string while a number is expected

In the following loop, if we type characters as the cin input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explain to me why this occurs?

When we use cin, if the input is not a number, then are there ways to detect this to avoid abovementioned problems?

unsigned long ul_x1, ul_x2;  while (1) {   cin >> ul_x1 >> ul_x2;   cout << "ux_x1 is " << ul_x1 << endl << "ul_x2 is " << ul_x2 << endl; } 
like image 974
chanwcom Avatar asked May 03 '11 02:05

chanwcom


People also ask

Can CIN be used for strings?

Inputting a stringYou can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.

Can you use CIN in a for loop?

Just add the cin inside the while loop, and the program will always wait you to write something. Example: int i; do{ cin>>i cout<<"num is smaller than 100"; } while(i<100); (Btw, idk if this code actually works.)

What is infinite while loop in C++?

While Loop condition is a boolean expression that evaluates to true or false. So, instead of providing an expression, we can provide the boolean value true , in place of condition, and the result is a infinite while loop.


2 Answers

Well you always will have an infinite loop, but I know what you really want to know is why cin doesn't keep prompting for input on each loop iteration causing your infinite loop to freerun.

The reason is because cin fails in the situation you describe and won't read any more input into those variables. By giving cin bad input, cin gets in the fail state and stops prompting the command line for input causing the loop to free run.

For simple validation, you can try to use cin to validate your inputs by checking whether cin is in the fail state. When fail occurs clear the fail state and force the stream to throw away the bad input. This returns cin to normal operation so you can prompt for more input.

  if (cin.fail())   {      cout << "ERROR -- You did not enter an integer";       // get rid of failure state      cin.clear();        // From Eric's answer (thanks Eric)      // discard 'bad' character(s)       cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');    } 

For more sophisticated validation, you may wish to read into a string first and do more sophisticated checks on the string to make sure it matches what you expect.

like image 108
Doug T. Avatar answered Sep 22 '22 10:09

Doug T.


Attention

Please pay attention to the following solution. It is not complete yet to clear the error in your case. You will still get an infinite loop!

if (cin.fail()) {      cout << "Please enter an integer";      cin.clear(); } 

Complete Solution

The reason is you need clear the failed state of stream, as well as discard unprocessed characters. Otherwise, the bad character is still there and you still get infinite loops. You can simply can std::cin.ignore() to achieve this. For example,

if (cin.fail()) {          cout << "Please enter an integer";          // clear error state          cin.clear();          // discard 'bad' character(s)          cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } 

Another Solution

You can also use getline and stringstream to achieve. Here is a brief example.

   string input;    while (1)    {       getline(cin, input);       stringstream(input) >> x;       cout << x << endl;    } 
like image 41
Eric Z Avatar answered Sep 26 '22 10:09

Eric Z