在这段代码中,我有几个用于用户输入的查询。如果有一个无效的输入,比如"r"而不是4,我希望我的程序说"无效输入",并要求另一个用户输入。我试了很多,但都没能成功。我评论了代码中有问题的位置。谢谢你的帮助。
#include <stdio.h>
int main()
{
double Operand1;
double Operand2;
int Menuchoice;
int Input;
char Dummy;
double Result;
do
{
printf("Simple Calculatorn");
printf("========================n");
printf("n");
printf("1. Additionn");
printf("2. Subractionn");
printf("3. Multiplicationn");
printf("4. Divisionn");
printf("9. Quitn");
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 = %lfn", Operand1, Operand2, Result);
break;
case 2:
case 3:
case 4:
default: printf("No valid input!n");
break;
}
}
}while (Menuchoice != 9);
return 0;
}
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: %fn",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
。