c - 如何检测用户是否在菜单中输入字母

标签 c c99

我正在为游戏制作菜单,当我测试程序并输入字符或字符串时,程序将永远运行默认值,

我尝试使用 strcmp(x,y) 函数,但这似乎对我不起作用。

int main(void) {
    int run = 1;
    int choice;
    do
    {
        printf("options: \n1. foo \n2.Bar \n");
        scanf("%d", &choice")
        switch (choice) {
        case 1: printf("hello world \n");
            break;
        case 2: printf("Hello World \n");
            break;
        default: printf("enter a valid option");
            break;
        }
        } while (run == 1);
return 0;
}

最佳答案

正如评论中所说,您从未设置过选择,因此它的值是未定义的,并且其用法是未定义的行为

例如替换

        printf("options: \n1. foo \n2.Bar \n");

    printf("options: \n1. foo \n2.Bar \n");
    if (scanf("%d", &choice) != 1) {
      /* not an integer, byppass all up to the newline */
      int c;

      while ((c = getchar()) != '\n') {
        if (c == EOF) {
          fprintf(stderr, "EOF");
          return -1;
        }
      }
      choice = -1;
    }

或者更简单地获取一个字符而不是一个int:

    char choice;
    ...
    printf("options: \n1. foo \n2.Bar \n");
    if (scanf(" %c", &choice) != 1) {
      fprintf(stderr, "EOF");
      return -1;
    }
    ...
    case '1':
    ...
    case '2':
    ...

注意 %c 之前的空格以绕过空格和换行符,在这种情况下,当然将 case 1 替换为 case '1'case 2 by case '2'

始终检查 scanf 的结果,如果您只是执行 scanf("%d", &choice); 并且用户不输入您的程序将循环的数字,而不会结束询问选择并指示错误,将不会获得更多输入,因为非数字不会被绕过,因此scanf将获得全部内容时间。

另请注意

  • 选项 1 和 2 都执行 printf("hello world\n")
  • run 从未被修改,因此 do ... while (run == 1); 无法结束,也许您想设置 run对于情况 1 和 2 为 0(我的意思是一个值!= 1)?
<小时/>

示例:

#include <stdio.h>

int main(void) {
  int run;
  char choice;

  do
  {
    run = 0;
    puts("options:\n 1. foo \n 2. Bar");
    if (scanf(" %c", &choice) != 1) {
      fprintf(stderr, "EOF");
      return -1;
    }

    switch (choice) {
    case '1': 
      printf("hello foo\n");
      break;
    case 2:
      printf("Hello bar \n");
      break;
    default:
      run = 1;
      puts("enter a valid option");
      break;
    }
  } while (run == 1);

  printf("all done with choice %c\n", choice);
  return 0;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
options:
 1. foo 
 2. Bar
a
enter a valid option
options:
 1. foo 
 2. Bar
33
enter a valid option
options:
 1. foo 
 2. Bar
enter a valid option
options:
 1. foo 
 2. Bar
1
hello foo
all done with choice 1
pi@raspberrypi:/tmp $ 

关于c - 如何检测用户是否在菜单中输入字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783181/

相关文章:

c - 限制指针问题

c - 为什么预定义宏 __STDC_VERSION__ 未定义?

c++ - 使用 OpenGL 绘制随机点/星星?

c - 为什么对结构使用不同的不同标记和 typedef?

c# - 如何在不取消链接的情况下关闭 shm_open 文件描述符?

c - 评估后左值不指定对象?

c - 是否可以(合法)在复合文字中分配匿名 union ?

c - 几个 getchar 电话

c - 使用 C 语言编写的套接字的服务器/客户端工作流程

c - 在函数开头声明变量有什么好处吗?