我正在制作一个列出选项1-3的菜单。期望用户输入整数。
scanf("%d", &select_option)
如果用户输入char(例如“a”,或“asd”表示长字符串,或“1a2”之类的混合)而不是预期的int,我如何提示错误?感谢。
注意:当用户输入'char',如'a','asd'时,由于某种原因,代码会进入无限循环。
这是我的程序(最小例子):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
while(select_option != 4)
{
switch(select_option)
{
case 1:
printf("You like tennis! Nice! \n");
break;
case 2:
printf("You like badminton! Nice!");
break;
case 3:
printf("You like basketball! Nice!");
break;
default:
system("clear");
printf("Invalid option. Please re-enter your choice (1-4).\n");
}//end switch
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
}//end while
}//end main
答案 0 :(得分:1)
你可以这样做:
#include <stdio.h>
int main(void) {
int v;
int ret = scanf("%d", &v);
if(ret == 1)
printf("OK, %d\n", v);
else
printf("Something went wrong!\n");
return 0;
}
我利用scanf()
的返回值,并根据该值,我做了一个假设。对于“1a2”的情况,这将失败,但对于“12”和“a”将成功。
然而,这是一个广泛的问题,我个人采用的方式是:
fgets()
读取输入。strtol()
)。答案 1 :(得分:1)
我假设你是初学者。您可以使用 Switch Case ,它通常用于创建菜单,并根据用户的选择执行特定情况。 我将向您展示一个小例子。
#include<stdio.h>
#include<conio.h>
int main()
{
int n;
printf("Select the sports u want to do\n");
printf("1.Tennis\n2.Karate\n3.Football\n");
scanf("%d",&n);
Switch(n)
{
case 1:printf("You chose Tennis\n");
break; //To prevent from all cases being executed we use
//break which helps from coming out of a loop
case 2:printf("You chose Karate\n");
break;
case 3:printf("You chose Football\n");
break;
default:printf("Please enter an appropriate number !");
//Cases which dont match with the input are handled by default !
}
}
还要让用户输入输入,直到他想要退出时添加一个带变量的while循环!
我希望这有帮助!