【问题标题】:Switch Statement stuck in an infinite loop when using the default case c++使用默认情况 c++ 时,Switch 语句卡在无限循环中
【发布时间】:2019-01-10 23:08:38
【问题描述】:

我最近刚开始学习 C++ 并创建了一个简单的 RPG 游戏以供练习。但我遇到的一个问题是switch 语句在使用default 案例时陷入了无限循环。

我的代码基本上是这样的:

while (cond)
{
    //Ask user for input 1-4
    cin >> choice;
    switch(choice - 1)
    {
         case 0:
               //Action
               break;
         case 1:
               //Action
               break;
         case 2:
               //Action
               break;
         case 3:
               //Action
               break;
         default:
              cout << "You entered an invalid command. Try again." << endl;
    }
}

最终cond会在通过//action将敌人HP降至0或以下时变为false。

但是,当我输入随机键时,它确实会转到默认情况并再次要求用户输入,但会跳过 cin &gt;&gt; choice; 并在无限循环中再次重播默认情况。

我怎样才能避免这种情况?

【问题讨论】:

标签: c++


【解决方案1】:

您需要清除输入状态,然后忽略无效的垃圾。

default:
    cout << "You entered an invalid command. Try again." << endl;
    cin.clear();
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

另请参阅,此答案:Why would we call cin.clear() and cin.ignore() after reading input?

【讨论】:

  • 在调用ignore()丢弃一行时,习惯上使用std::streamsize而不是int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多