gpt4 book ai didi

c - 验证输入并再次询问是否无效

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

在这段代码中,我有几个用户输入查询。如果有无效输入,如“r”而不是 4,我希望我的程序说出“无效输入”并要求另一个用户输入。我尝试了很多,但我无法让它工作。我评论了代码中有问题的位置。感谢您的帮助。

#include <stdio.h>

int main()
{
double Operand1;
double Operand2;
int Menuchoice;
int Input;
char Dummy;
double Result;

do
{

printf("Simple Calculator\n");
printf("========================\n");
printf("\n");
printf("1. Addition\n");
printf("2. Subraction\n");
printf("3. Multiplication\n");
printf("4. Division\n");
printf("9. Quit\n");


Input = scanf("%i", &Menuchoice); // At this point I want to check if there is a valid input and
do scanf("%c", &Dummy); // if not the programm should ask again
while (Dummy != '\n');

if(Input)
{
switch(Menuchoice)
{
case 1: printf("Type in the first operand:\n");
scanf("%lf", &Operand1) // Here I want to validate the input
printf("Type in the second operand:\n"); // again and the programm should also ask
scanf("%lf", &Operand2) // again if it was invalid
printf("%lf + %lf = %lf\n", Operand1, Operand2, Result);
break;
case 2:
case 3:
case 4:
default: printf("No valid input!\n");
break;
}
}

}while (Menuchoice != 9);

return 0;
}

最佳答案

scanf 的手册页:

On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.

所以这是一个可以帮助您解决问题的示例:

#include <stdio.h>

int main (int argc, char* argv)
{
double o;
int res;

// To illustrate, I chose to set up an infinite loop.
// If the input is correct, we'll "break" it
while(1)
{
printf("Enter a double: ");
res = scanf("%lf",&o);

// Success = 1 read input
if (res == 1)
{
printf("Yahoo, got it right: %f\n",o);
break; // We exit the loop
}

// Ah, we failed
printf("Please retry.\n");
// popping the CR character to avoid it to be got by the next scanf()
getchar();

// Here we go for another loop.
}

// Good, we got our double.
printf("Hey, sounds like we got outside this infinite loop.\n");
}

例子:

user@so:~$ ./a.out 
Enter a double: r
Please retry.
Enter a double: f
Please retry.
Enter a double: 6.543
Yahoo, got it right: 6.543000

请记住,此检查并不完美。例如,"frg6sgg" 将成功并被 printf() 显示为 6.0000000

关于c - 验证输入并再次询问是否无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53438567/

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