【发布时间】:2013-08-04 21:19:25
【问题描述】:
我正在尝试在我的第一个 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的类型是什么? -
我已尝试将其转换为字符串,但问题仍然存在。
-
生命类型可能是整数或其他东西。使用 cin.get() 而不是 cin,因为您的返回值(按回车键)保留在标准输入中...
-
好吧,使用 cin.get 它不会无限重复。但是,它在循环中给了我大约 5 或 6 次错误消息,并且在停止时甚至拒绝接受正常数字。
-
为什么不使用命名空间标准?
标签: c++ while-loop infinite-loop cin