[我正在制作的游戏开始时,玩家需要给该角色进行不同类别的得分时要给予积分(例如辐射的特殊效果)。但是,如果输入字母而不是数字,则cin
会失败,并且程序会崩溃并出现异常。
尝试用std::cin.fail()
检查但没有运气:
for(int i = 0; i < 5; i++) {
switch(i) {
case 0:
cout <<"\n\nStrength (How strong you are)";
cout <<"\nHow many points (you have " << total_SKILL_points << " left): ";
std::cin >>Strength;
if(std::cin.fail()) {
std::cin.clear();
cout <<"\n\nPlease enter a number!";
i--;
break;
}
total_SKILL_points = total_SKILL_points - Strength;
break;
// keeps going, that's why no closing } for switch or for loop.
如果有的话,检查信件是否已传递给cin
的正确方法是什么?
如果输入错误,您可以清除错误标志,并忽略其余行。
#include <iostream>
#include <limits>
#include <list>
#include <string>
int main() {
int total_SKILL_points = 100;
int Strength;
while(std::cin) { // check that cin is in a good state
std::cout << "\n\nStrength (How strong you are)";
std::cout << "\nHow many points (you have " << total_SKILL_points
<< " left): ";
if(std::cin >> Strength) { // check that cin is in a good state after extraction
// success
break;
} else {
// failure
std::cout << "\n\nPlease enter a number!";
// clear error flags
std::cin.clear();
// ignore rest of line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
}