gpt4 book ai didi

c - 菜单循环中 scanf 的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 01:39:04 25 4
gpt4 key购买 nike

下面是一个简单菜单的代码。如果用户输入了无效选项(4 或“o”),则应重新打印菜单并显示错误消息。该代码在用户输入数字时有效,但是当用户在选项中输入字母或字符串时它会失败(无限循环)。我的猜测是,在产生奇怪行为的循环情况下,内存被覆盖了。有人可以帮我解决吗?谢谢你

int inmenu = 1;
while (inmenu){
//Menu
printf("User: %s %s\n", user.firstname, user.lastname);
printf("0) Exit\n1) List Friends\n2) Add Friend\n3) Delete Friend\nWhat would you like to do? ");
int option;
scanf("%i", &option);
if(option == 0)
inmenu = 0;
else if (option == 1)
defaultPrint(friends, numfriends, NULL);
else if (option == 2){
//addfriend
char *name = (char *) malloc(sizeof(char) * 256);
int birthdate;
printf("Enter first name: ");
scanf("%s", name);
printf("Enter last name: ");
scanf("%s", name);
printf("Enter birthdate: ");
scanf("%i", &birthdate);

}
else if (option == 3){
//deletefriend
defaultPrint(friends, numfriends, NULL);
int n;
printf("What friend would you like to delete? ");
scanf("%i", &n);
}
else
printf("ERROR: Invalid option %i\n", option);
}

测试输入:

0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
What would you like to do? 4
ERROR: Invalid option 4
0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
What would you like to do?

(正确行为)

0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
What would you like to do? o
What would you like to do? ERROR: Invalid option 4
0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
...

(不正确的行为在无限循环中不断打印相同的最后 5 行)

最佳答案

为什么要使用scanf?如何使用getchar,检查范围,看是否为0-4,如果不是,则错误信息。

关于c - 菜单循环中 scanf 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8998948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com