c++ - Ignore user input outside of what's to be chosen from -


i have program in user must make selection entering number 1-5. how handle errors might arise them entering in digit outside of bounds or character?

edit: sorry forgot mention in c++

be careful this. following produce infinite loop if user enters letter:

int main(int argc, char* argv[]) {   int i=0;   {     std::cout << "input number, 1-5: ";     std::cin >> i;   } while (i <1 || > 5);   return 0; } 

the issue std::cin >> i not remove input stream, unless it's number. when loops around , calls std::cin>>i second time, reads same thing before, , never gives user chance enter useful.

so safer bet read string first, , check numeric input:

int main(int argc, char* argv[]) {   int i=0;   std::string s;   {     std::cout << "input number, 1-5: ";     std::cin >> s;     = atoi(s.c_str());   } while (i <1 || > 5);   return 0; } 

you'll want use safer atoi though.


Comments

Popular posts from this blog

Delphi Wmi Query on a Remote Machine -