Abhishek Guru
Abhishek Guru

Reputation: 603

In this infinite loop which terminates when 0 is entered, when anything outside the range of int is entered program misbehaves

In this infinite loop which terminates when 0 is entered, when I'm entering anything outside the range of int say 2147483648(range of int + 1) this program keeps on running infinitely.

 #include<iostream>
    using namespace std;
    int main(){
     int n;
     while(1){

           cout<<"enter n: ";
           cin>>n;
           if(n==0)   break;

    }

    return 0;
    }

Upvotes: 0

Views: 472

Answers (2)

Jeremy Friesner
Jeremy Friesner

Reputation: 73294

From the documentation on std::basic_istream::operator>>:

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. [until C++11]

So the behavior you are seeing is caused by the failbit, which causes subsequent calls to the >> operator to fail immediately.

Interestingly, the behavior was changed for C++11 and later:

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set. [Since C++11]

Upvotes: 3

john
john

Reputation: 88027

Since you don't test for any errors it's not surprising that your code misbehaves.

Try this

while(1){

       cout<<"enter n: ";
       cin>>n;
       if (!cin || n==0)   break;

}

!cin is a test if cin is in an error state. This would happen (for instance) if the last input failed because what was entered could not be converted to an int.

Upvotes: 2

Related Questions