如何检查std :: cin是否失败

问题描述 投票:0回答:1

[我正在制作的游戏开始时,玩家需要给该角色进行不同类别的得分时要给予积分(例如辐射的特殊效果)。但是,如果输入字母而不是数字,则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的正确方法是什么?

c++ cin
1个回答
0
投票

如果输入错误,您可以清除错误标志,并忽略其余行。

#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');
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.