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

How to detect if user inputs a letter inside a menu

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

我曾尝试使用 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;
}

打印后必须加scanf语句"Options :..."

#include <stdio.h>

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\n");
                break;
        }


    }while (run == 1);

    return 0;
}

如果您需要检查输入的值是否为数字,您可以使用 isdigit() 函数。

如评论中所述,您从未设置 choice,因此其值未定义且其用法未定义行为

例如替换

        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 之前的 space 绕过 space 和换行符,在这种情况下当然用 case '1' 和 [= 替换 case 1 18=] 来自 case '2'

Always 检查 scanf 的结果,如果你只是 scanf("%d", &choice); 而用户没有输入你的程序的数字将循环而不结束询问选择并指示错误,将不会获得更多输入,因为非数字被 not 绕过,因此 scanf 将得到一直都是。

另请注意

  • 选项 1 和 2 都符合 printf("hello world \n")
  • 运行 永远不会被修改所以 do ... while (run == 1); 不能结束,也许你想设置 运行 到 0(我的意思是一个值!= 1)对于情况 1 和 2 ?

示例:

#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 $