【问题标题】:created a switch case for int argument with a default case. but default case is unable to handle properly the chars使用默认情况为 int 参数创建了一个 switch 情况。但默认情况下无法正确处理字符
【发布时间】:2015-08-28 02:53:40
【问题描述】:

这里是代码

int miscellaneous::printWelcomeScreen(){
    int ch;
    cout<<"Tic Tac Toe"<<endl<<endl;
    cout<<"1. Play Game "<<"2. How to Play "<<"3. Credits "<<endl;
    cout<<endl<<"Enter Your Choice"<<endl;
    cin>>ch;
    choiceSelection(ch);
    return 0;
}

int miscellaneous::choiceSelection(int ch){
    switch(ch){
    case 1: break;
    case 2: showHelp();break;
    case 3: showCredits();break;
    default: {
            cout<<"Wrong Choice dude!! Use your keyboard Properly next time";
            printWelcomeScreen();
            break;
            }
    }
    return 0;
}

当我给出一个 int 输入时,默认情况下工作得很好, 但是当我输入一个字符时,默认情况开始无限循环运行。

为什么会这样? 我什至尝试在传递给 switch 之前解析 ch。

【问题讨论】:

  • 您最好使用char ch 而不是int ch 并更新switch 以检查字符'1''2''3'

标签: c++


【解决方案1】:

当您输入 char 值时,cin(input) 操作失败,因为输入了 ch 类型以外的内容。 所以这里他们需要检查输入操作是否失败。为此使用 cin.fail() 将在 cin 失败时设置。

int miscellaneous::printWelcomeScreen()
{
    int ch  = 0;
    cout<<"Tic Tac Toe"<<endl<<endl;
    cout<<"1. Play Game "<<"2. How to Play "<<"3. Credits "<<endl;
    cout<<endl<<"Enter Your Choice"<<endl;
    cin >> ch;
   if(cin.fail() != 0)
   {
       std::cout << "Hey! That's not valid input! Try again.\n\n"
       cin.clear();
       cin.ignore(10000,'\n');
   }
   cout <<  " ch = " << ch << endl;
   choiceSelection(ch);
   return 0;
}

当 cin 检查并发现失败时,需要清除 cin 上的错误标志。它的详细信息在此链接中进行了说明: Why would we call cin.clear() and cin.ignore() after reading input?.

【讨论】:

  • 谢谢,它成功了。我应该在每次输入后调用 cin.clear() 吗?
  • @VikasKumar 是的,检查读取操作是否成功是一个好习惯。如果它失败了,那么你需要调用 cin.clear()。
【解决方案2】:

您没有检查读取是否失败。因此,如果std::cin 失败一次,它将隐式失败,直到情况得到处理,从而导致无限递归和最终的堆栈溢出。改用这样的东西。

int miscellaneous::printWelcomeScreen() {
    int n;
    bool again;

    do {
        again = false;

        std::cout << "Tic Tac Toe\n\n1. Play Game\n2. How to Play\n3. Credits\n\nEnter your choice: ";
        std::cin >> n;
        if(std::cin.fail() || !choiceSelection(n)) {
            again = true;
            std::cout << "Hey! That's not valid input! Try again.\n\n"

            continue;
        }
    } while(again);

    return 0;
}

bool miscellaneous::choiceSelection(int n) {
    switch(n) {
        case 1:
            // ...
            break;

        case...

        default:
            return false;
    }

    return true;
}

【讨论】:

    猜你喜欢
    • 2012-02-29
    • 2020-07-11
    • 2010-12-02
    • 2012-11-24
    • 2011-11-21
    • 2014-08-21
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多