当我输入一个非整数值时,它会导致无限循环。我需要更换 scanf 吗?如果是这样,我该怎么做。
int num=1;
if(num==1){
int slct;
printf("\n\tWelcome");
printf("\n1. Login\n2. Register\n3. Account\n4. Exit\n");
SELECTION: ;
printf("\n\tEnter a number:");
scanf("%d",&slct);
if (slct == 1){}
else if (slct == 2){}
else if (slct == 3){}
else if (slct == 4){
return 0;
} else {
goto SELECTION;
}
}
您需要检查返回值scanf
并刷新输入:
#include <stdbool.h>
#include <stdio.h>
int main()
{
bool done = false;
while (!done) {
printf("\n\tWelcome\n");
printf("1. Login\n");
printf("2. Register\n");
printf("3. Account\n");
printf("4. Exit\n\n");
printf("Enter a number:");
int selection;
int result = scanf("%d", &selection);
if (EOF == result) {
done = true;
}
else if (1 != result) {
printf("You did not enter a valid number\n");
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
done = (c == EOF);
}
else if (1 == selection) {
printf("You chose login\n");
}
else if (2 == selection) {
printf("You chose register\n");
}
else if (3 == selection) {
printf("You chose account\n");
}
else if (4 == selection) {
done = true;
}
else {
printf("Please pick a number between 1 and 4\n");
}
}
}
在格式字符串scanf("%d",&slct);
就是%d
这意味着你想读的数字。
当您输入数字以外的其他内容时,scanf
返回 0 表示读取了零个数字。
如果 scanf 在尝试读取输入时遇到文件结尾(输入 control-D),则它返回特殊值 EOF。
此外, scanf 不会消耗不正确的输入,因此您需要明确刷新它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句