首页 > 解决方案 > 如何检测用户是否在菜单内输入字母

问题描述

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

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

标签: cc99

解决方案


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

例如替换

        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 1case '1'case 2case '2'

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

另请注意

  • 选择 1 和 2 都可以printf("hello world \n")
  • run永远不会被修改,所以do ... while (run == 1);不能结束,也许你想为案例 1 和 2 将run设置为 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 $ 

推荐阅读