Problem with input in c++ -


i have basic question want take integer input in range user. if user gives string or char instead of integer. program goes infinite loop.

my code that

cin >> intinput;  while(intinput > 4 || intinput < 1 ){     cout << "wronginput "<< endl;     cin >> intinput;  } 

i allowed use c++ libraries not c libraries.

the solution answer read lines standard input.

std::string input; int value = 0; {         // read user's input. typed line, read line.     if ( !std::getline(std::cin,input) )     {         // not read input, handle error!     }          // attemp conversion of input integer.     std::istringstream parser(input);     if ( !(parser >> value) )     {         // input wasn't integer, it's ok, we'll keep looping!     } }     // start on while ((value > 4) || (value < 1)); 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -