Search code examples
c++while-loopinfinite-loop

Getting infinite loop in C++ while-loop, why is this happening?


#include<iostream>
using namespace std;

int main()
{

 int val1=0, val2=0;
 bool a=true;
 
 while(a)
 {
  cout << "Enter 2 numbers: " << endl;
  cin >> val1 >> val2;
  if( val1=='|' || val2=='|' ) a=false; //terminate loop
  else cout << val1 << " " << val2 << endl;
 }

}

Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the program when a terminating '|' is entered.

This is what i want to program, code works well until entering non digit charachter. even '|' makes it to go in infinite loop. I just want to know why? Could not figure it out


Solution

  • cin >> val1 >> val2;
    

    The >> overload for a std::istream expects to read an integer number on input. An integer number is, well, an integer number. It would be 0, 1, -5, or 42. These are integer numbers.

    The | character is not an integer number.

    I just want to know why?

    Because when an input operation fails, in this manner, the input stream is set to a failed state. When an input stream is in a failed state all further attempted formatted input operations immediately fail without setting the target of the formatted input operation.

    So, entering | on input leaves val1 and val2 unchanged, and the stream in a failed state. The input stream remains in a failed state, and the same thing happens on the next iteration of the loop.

    And that's why you get an infinite loop.

    if( val1=='|' || val2=='|' )
    

    This line does not do what you think it does. val1 and val2 are integers. A character is also an integer, interpreted as an ASCII code, so what this really does is compare val1 and val2 to the code for the Ascii character |. But, for the reasons explained above, inputting | does not set an int value to its ASCII code, >> does not work this way. It leaves the input stream in a failed state, >> on an int expects to read an actual, real number, something that would correspond to the number of fingers you have, if you had a corresponding number of fingers (or short the requisite amount in case of a 0 or a negative number, I suppose...)