Home > Back-end >  Why isn't cin taking input after an invalid type is passed to the variable
Why isn't cin taking input after an invalid type is passed to the variable

Time:04-17

It is a menu driven program and works completely fine when an int is passed to the variable options but runs into an infinite loop when char is passed.

int main(){

while(true){
    int options{0};
    cout<<"\nYour choice >>";
    cin>>options;         //this line doesnt execute after any char(say r) is given as an input
    switch(options){
        case 1:login();break;
        case 2:signup();break;
        case 3:return 0;
        default:cerr<<"Please enter a valid choice"<<endl;
    }
}


txt.close();
return 0;

} I tried to debug and here is the problem

Breakpoint 1, main () at main.cpp:16 16 cin>>options; (gdb) p options $1 = 0 (gdb) c Continuing. Your choice >>r

Breakpoint 2, main () at main.cpp:17 17 switch(options){ (gdb) p options $2 = 0 (gdb) c Continuing.

Breakpoint 3, main () at main.cpp:21 21 default:cerr<<"Please enter a valid choice"<<endl; (gdb) p options $3 = 0 (gdb) c Continuing. Please enter a valid choice

Breakpoint 1, main () at main.cpp:16 16 cin>>options; (gdb) c Continuing.

Breakpoint 2, main () at main.cpp:17 17 switch(options){ (gdb) Quit (gdb)

After line 16 its going to line 17 without asking for input from user

CodePudding user response:

This is because of how C streams work.
When there is an error related to the internal logic of a stream operation (such as expecting an int but getting a char), its failbit is set.
When one of the stream bits (failbit, badbit, eofbit) are set, stream operations will not do anything.
To reset the iostate, you can use the clear method of the stream:

std::cin.clear();

This will set goodbit on which means the other 3 bits are off and you can use the stream.
To check the these bits, you can use the state methods: good(), fail(), bad(), eof()
But keep in mind that the streams have a conversion operator to bool which returns !fail() so you can use streams in a boolean context:

char c;
while (std::cin >> c) {...

And if you want to skip the bad input line, you can do this after clear():

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

This will basically skip all characters in the stream's buffer until it reaches '\n'. The first parameter is how many characters to skip until EOF or '\n', which we will set to the max size possible.

  • Related