【问题标题】:How to prevent non-integer input in c? [duplicate]如何防止c中的非整数输入? [复制]
【发布时间】:2021-10-22 11:17:33
【问题描述】:

我正在尝试运行一个程序,用户只能输入 1 或 2。如果用户输入任何其他数字或字母,它应该提示用户再次输入输入。我已经尝试了以下代码,如果用户输入一个不是 1 或 2 的整数,它就可以工作,但是如果输入任何字母,整个程序都会变得混乱。我试图验证

if == 0 但也不起作用。有人知道吗?

int getUserInput(){

printf("1: You have chosen 1.\n");
printf("2: You have chosen 2.\n\n");

printf("Enter an option: ");
scanf("%d", &userSel);

if(userSel!= 1 && userSel!= 2){
    
    printf("You have entered an invalid input. Please try again.\n");
    getUserInput();
}
else{
    printf("Enter a number: ");
    scanf("%d", &userNo);
}

printf("userSelection: %d\n", userSel);
printf("1userNumber: %d\n", userNo);

return 0; 
}

【问题讨论】:

  • 而不是scanf(any_format, ...),使用fgets() 将用户输入的 读入字符串。然后处理那个 string.

标签: c if-statement


【解决方案1】:

也许你可以这样 scanf 设置变量,仅当输入为整数时才会保存用户输入。您可以在此处使用与您的问题类似的堆栈溢出链接!

How to scanf only integer?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多