我正在使用switch语句创建此程序,该语句将根据用户是否输入数字0-10来指定字母等级。如果用户输入的数字不是0-10,程序将输出错误消息并具有用户重新进入。但是,如果用户输入一个字符,程序将以默认情况循环。我希望它从默认情况下输出一次错误消息,并让它们在输入字符时重新输入。我不确定为什么它会在输入字符时循环默认情况。
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
}
}
return 0;
}
答案 0 :(得分:2)
尝试类似:
func frameForBarButton(btn: UIBarButtonItem) -> CGRect {
let view: UIView = btn.valueForKey("view") as! UIView
return view.frame
}
答案 1 :(得分:1)
这将清除无效输入上的输入缓冲区并允许重试。
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
if ( r != 1) {//r == 1 is successful input of integer
grade = -1;//reset grade on invalid input
}
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
while ( getchar() != '\n');//clear input buffer
}
}
return 0;
}
答案 2 :(得分:0)
你的代码总是循环的原因是因为除了杀死程序之外没有办法退出break
。请注意,switch
只会突破最内层的bool valid_grade = false;
while(!valid_grade && (r = scanf("%i", &grade)) != EOF)
{
valid_grade = true;
switch(grade)
{
case 10:
// unchanged from your code
default:
valid_grade = false;
printf("Invalid score, please re-enter\n");
}
}
或循环。
打破多个级别的最简洁方法是使用标志。做你想做的事的一种方法是:
Select Application_Number
,Id_Number1
,'Alias' + CAST( ROW_NUMBER()
OVER (ORDER BY Application_Number) AS Varchar) AS Name
FROM Table Name