Я пытаюсь закодировать простой вопрос и средство проверки чисел в свою первую программу на C++. Проблема в том, что когда я набираю строку типа один, два или три, программа превращается в бесконечный цикл и игнорирует функцию cin для переназначения жизней на число.
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
while(lives != 1 && lives != 2 && lives != 3 && !isdigit(lives))
{
cout << "You need to input a number, not words." << endl;
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
}
Вот мой текущий код с вашими предложениями:
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
std::cin.ignore();
std::cin.clear();
if (std::cin >> lives)
{
while(lives != 1 && lives != 2 && lives != 3)
{
cout << "You need to input a number, not words." << endl;
cout << "How many lives would you like 1 (hard), 2 (medium), or 3 (easy)?" << endl;
cin >> lives;
}
}
lives
? - person Borgleader   schedule 03.08.2013