C++ 如何实现带有数字和字母选项的菜单

C++ How to Implement Menu with Number and Letter Choices

我想使用 C++ 中的菜单,其中包含字母和数字选项。例如,输出可能是:

========================
(1) Do something
(2) Do something
(a) Do something
(b) Do something
========================

是否有一种方法可以测试用户输入以确定它是 char 还是 int 并相应地处理它?

如果我使用:

int choice;
cin >> choice;

而用户输入的是一个字符,cin当然会return报错。我正在寻找一种简单的方法来测试用户输入的数字或字符,并让程序根据该确定做出不同的反应。

[更新]

我找到了我要找的答案。这是我的做法:

string choice;
cout << "Your choice: ";
cin >> choice;

if( isdigit(choice[0]) )
{
    theInt = stoi(wChoice);
    // do something with int
}
else if( choice[0] = 'a' )
    // do menu option a

你最好使用ctype.h中的方法isdigit检查字符是否为十进制数字字符,以及isalpha方法检查字符是否为字母。

"For example, there could be options: 1, 2, 3, n, s."

我看到的最简单的解决方案是有一个像

这样的菜单选择代码
char choice;
std::cin >> choice;

switch(choice) {
case `1`:
   // Do menu option one
   break;
case `2`:
   // Do menu option two
   break;
case `3`:
   // Do menu option three
   break;
case `n`:
   // Do menu option "n"
   break;
case `s`:
   // Do menu option "s"
   break;
}

如果您需要处理大于 9 的数字选择,您只需使用 std::string 作为输入字段:

std::string choice; // <<<    
std::cin >> choice;

反过来 switch 语句不能再使用,您必须将其更改为 if/else if/else 级联:

if(choice == "1") {
   // Do menu option one
}
else if(choice == "2") {
   // Do menu option two
}
// ...
else if(choice == "42") {
   // Do menu option fortytwo
}
else if(choice == "n") {
   // Do menu option "n"
}
else if(choice == "s") {
   // Do menu option "s"
}

为此,您需要将输入作为字符串读入,然后对其进行解析以查看它是字母字符还是数字字符串。类似于此(警告,我主要是 C 程序员,所以使用 C 字符串而不是真正的字符串):

#define INPUT_SIZE 8
char input[INPUT_SIZE]; // change size as appropriate
cin.getline(input, INPUT_SIZE);

if (cin.good())
  if(input[0] >= '0' && input[0] <= '9') {
      int value = atoi(input);
  } else if(input[0] >= 'a' && input[0] <= 'z') {
      char value = input;
  }
}

当然,值需要不同的名称和实际代码路径来处理它们,尤其是因为 C++ 没有我所知道的良好的内置 "either" 类型。

或者,将所有内容都视为字符,假设所有数字选项都是单个字符,并测试为“0”而不是 0。