This question has already been answered:

I write a while in it there is a switch (the choice of case depends on a variable of type int ) if you enter a letter / symbol then the program crashes. It is necessary to implement a test for characters / letters ... Google, but did not find the answer intelligible. I myself sort of understand that I need to verify the type of the variable assigned, but alas, I cannot implement it. Implementing a simple check for labor numbers was not, but the letters / symbols are already a problem ...

 while (ace) { std::cout << "Please select an action: "; std::cin >> a; switch (a) { case 1: { Sort1(); break; } case 2: { std::cout << "Hello 2" << std::endl; break; } case 3: { std::cout << "Hello 3" << std::endl; break; } case 4: { std::cout << "\nВы вышли из программы" << std::endl; system("pause"); ace = false; break; } default: std::cout << "Error" << std::endl; } } 

Reported as a duplicate by members αλεχολυτ , Community Spirit 1 Oct '16 at 14:06 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Code show, without this question does not make any sense. In any case, there are no problems with casting a character to an int in C ++, including the switch. And if the program "falls" (it falls, but does not follow the wrong branch of the algorithm), then the problem may not be at all in this. - PinkTux
  • @Pink Tux added, there is not something that it falls, but the text starts to run cyclically - goga

1 answer 1

 while( ace ) { std::cout << "Please select an action: "; std::string input; std::cin >> input; /* дальше переводим строку input в число. ошибка - ругаемся и вводим заново. получии валидный int - отдаём его в switch */ } 
  • Thanks, made :) - goga