gpt4 book ai didi

循环中的 C++ 开关在再次运行之前变为默认值

转载 作者:行者123 更新时间:2023-11-27 23:48:00 25 4
gpt4 key购买 nike

我的第一个 C++ 程序是命令行生存游戏。我在 while 循环中有一个 switch 语句,但它总是经过一次并在获取用户输入之前运行默认选择。这是相关代码:

int menu() {
while (true) {
char choice = getChoice();
switch(choice) {
case 'p':
{
system("clear");
Arena arena(player, difficulty);
arena.play();
}
break;
case 'u':
{
system("clear");
player.save();
player.init();
}
break;
case 'd':
{
system("clear");
changeDifficulty();
}
break;
case 'q':
{
system("clear");
return 0; // return menu(); in main()
}
default:
{
system("clear");
cout << nInvalid option! Press a key to choose: p, u, s, or q\n\n";
break;
}
}
}
}

getChoice 函数

char getChoice() {

cout << " Main Menu\n";
cout << "---------------------\n";
cout << "p - play game" << endl;
cout << "u - change user" << endl;
cout << "d - change difficulty" << endl;
cout << "q - quit\n" << endl;

char choice = getchar();
return choice;
}

通过一次并从默认选项运行代码后,一切正常。这是每次程序重新进入此循环时我得到的结果:

Invalid option! Press a key to choose: p, u, s, or q

Main Menu
---------------------
p - play game
u - change user
d - change difficulty
q - quit

提前感谢您的帮助!

最佳答案

假设您使用 the standard getchar function .

问题很可能是当您输入“选择”时,您输入了 'p'(例如),然后按 Enter 键。 Enter在输入中作为换行符 '\n'。因此,下次您调用 getChoice(它调用 getchar)时,您会读到该换行符。

基本上有四种方法可以解决:

  1. C 方式,使用 scanf 而不是 getchar,并要求 scanf 读取并丢弃前导空格(如换行符) :

    char choice;
    scanf(" %c", &choice);
    // Note space in front of the %c, which tells scanf to discard leading whitespace
  2. 读取字符,然后读取并丢弃所有其他内容,直到换行符。

  3. 整行读入字符串,并解析出字符。

  4. 使用 std::cin 和普通格式化输入运算符 >>>,因为这将跳过前导空格。

我真的推荐最后一种(第 4 种)方法。

关于循环中的 C++ 开关在再次运行之前变为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49003725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com