c - 如何检测用户是否在菜单内输入字母
问题描述
我正在为游戏制作菜单,当我测试程序并输入字符或字符串时,程序将永远运行默认值,
我曾尝试使用 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
case '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 $
推荐阅读
- python - python解析`ISO_8601`时间或时间间隔
- objective-c - 不能从多行的 NSTableView 中拖动
- java - Gradle 插件任务反射扫描插件的项目类文件而不是当前项目文件
- javascript - Ionic v1 / Angular - 从 DOM 中删除以前的离子视图
- php - 为什么我在 Wordpress 中使用 AJAX 时出现“GET 500”错误?
- openvpn - 如何在ubuntu的防火墙上添加SCTP
- c++ - 算术溢出:对 4 字节值使用运算符“*”,然后将结果转换为 8 字节值
- mysql - Mysql如何过滤上一个日历月的结果(不是上个月)
- python - 根据另一个df的列删除df行
- java - 使用哪些收集器?