如果玩家输入无效选择,如何阻止程序继续?

时间:2011-08-27 06:10:04

标签: c++

我创建了一个基于文本的游戏来帮助提高我的C ++技能,因为我对它很陌生。我正在努力学习基础知识。

这是程序。在switch语句中,如果一个人选择“3”,它将广播一个错误,说你只能选择“1”或“2”。 **问题是程序继续,并没有使人RECHOOSE选择。选择困难是正确的。

在玩家选择有效选择之前,我使用什么方法强制程序暂停?

谢谢!

#include <iostream>
using namespace std;

int main()
{
cout << "\tWelcome to my text based game!\n";
char userName[100];
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";

cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
int pickRace;
cout << "Pick your race: ";
cin >> pickRace;

switch (pickRace)
{
    case 1:
        cout << "You picked the Human race." << endl;
        break;
    case 2:
        cout << "You picked the Orc race." << endl;
        break;
    default:
        cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
}

int difficulty;
cout << "\nPick your level difficulty: \n";
cout << "1 - Easy\n";
cout << "2 - Medium\n";
cout << "3 - Hard\n";

cout << "Pick your level difficulty: ";
cin >> difficulty;

switch (difficulty)
{
    case 1:
        cout << "You picked Easy" << endl;
        break;
    case 2:
        cout << "You picked Medium" << endl;
        break;
    case 3:
        cout << "You picked Hard" << endl;
        break;
    default:
        cout << "Error - Invalid input, only 1,2 or 3 are allowed" << endl;
}

return 0;

}

3 个答案:

答案 0 :(得分:1)

您需要使用循环。将输入和开关包裹在循环中,并在输入有效时将其中断。

答案 1 :(得分:0)

使用do ... while循环,就像这样

int pickRace;
do
{
  cout << "Please pick your race: \n";
  cout << "1 - Human\n";
  cout << "2 - Orc\n";
  cout << "Pick your race: ";
  cin >> pickRace;
  switch (pickRace)
  {
    case 1:
      cout << "You picked the Human race." << endl;
      break;
    case 2:
      cout << "You picked the Orc race." << endl;
      break;
    default:
      cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
      break;
  }
}
while (pickRace != 1 && pickRace !=2);

当底部条件为真时(即当他们没有选择有效选项时),这将继续循环。

另一条评论。既然你是新手,你应该养成使用string而不是char数组的习惯。 Char数组将来会让你遇到各种各样的麻烦,所以现在开始使用字符串。学习坏习惯是没有意义的。

#include <string>

string userName;
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";

答案 2 :(得分:0)

你可以用do - while循环标记。该标志默认为false,因此只允许一次输入。如果需要输入由default情况确定和控制的另一个时间,则该标志设置为true,这使得循环再次迭代。在每次迭代开始时,标志被重置为false,因此每次假设这是最后一次。使用flag将使破坏操作变得非常简单,并避免复杂的while条件。

int flag = 0;

do
{

  cout << "Please pick your race: \n";
  cout << "1 - Human\n";
  cout << "2 - Orc\n";
  cout << "Enter Choice: ";
  cin >> pickRace;

  flag = 0;
  switch (pickRace)
  {
      case 1:
          cout << "You picked the Human race." << endl;
          break;
      case 2:
          cout << "You picked the Orc race." << endl;
          break;
      default:
          cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
          flag = 1;
  }
} while (flag);