[英]How can I repeat scanf in a switch-case scenario if some invalid input has been given?
I have the following code, where I expect the user to give eiher 's' or 'f' (case insensitive) as input: 我有以下代码,我希望用户将eiher的“ s”或“ f”(不区分大小写)作为输入:
/* ... snip ... */
char acc_type;
printf("\n\nENTER HERE\t : ");
scanf("%c",&acc_type);
switch (acc_type)
{
case 's':
case 'S':
printf("\n SAVING ACCOUNT");
break;
case 'f':
case 'F':
printf("\n FIXED ACCOUNT");
break;
default:
printf("\n INVALID INPUT!!! TRY AGAIN");
}
/* ... snip ... */
However, the default action doesn't allow me to repeat the whole switch
statement. 但是,默认操作不允许我重复整个
switch
语句。 How can I ask for input in his scenario again if the input wasn't valid? 如果输入无效,我该如何再次询问他的情况?
You need a loop, essentially (in pseudo-code): 您实际上需要一个循环(用伪代码):
good_input = 0;
while(good_input == 0) {
... prompt for input ...
if (input == good) {
good_input = 1;
}
}
Until something valid is entered, good_input
stays 0 and the while() loop continues to prompt for input. 在输入有效值之前,
good_input
保持为0,并且while()循环继续提示输入。 Once something good is entered, that flag changes and the code continues on to the next section. 输入好消息后,该标志将更改,代码继续进行到下一部分。
Put the part you want to repeat in a loop, like this: 将要重复的部分循环放置,如下所示:
bool inputOK = false;
do {
printf("\n\nType S to SAVING ACCOUNT");
printf("\nType F to FIX ACCOUNT");
printf("\n\nENTER HERE\t : ");
scanf("%c",&acc_type);
switch (acc_type)
{
case 's':
case 'S':
printf("\n SAVING ACCOUNT");
inputOK = true;
break;
case 'f':
case 'F':
printf("\n FIXED ACCOUNT");
inputOK = true;
break;
default:
printf("\n INVALID INPUT!!! TRY AGAIN");
break; // Note: it's wise to use break in EVERY case
}
} while (inputOK == false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.