在这段代码中,我有几个用于用户输入的查询。如果有一个无效的输入(例如“ 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;
}
答案 0 :(得分:2)
scanf
的手册页:
成功后,这些函数将返回输入项的数量 成功匹配并分配的;如果发生早期匹配失败,则该数目可能小于或小于所提供的数目。
因此,这里有一个示例可以帮助您解决问题:
#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"
将成功,并由6.0000000
显示为printf()
。