我需要为用户编写一个脚本,输入0到10之间的分数,刷新输入错误,如果用户输入,然后使用switch语句,告诉用户他/她得到了什么等级。
这是我的剧本:
...
int main()
{
int input; // input from user
printf("Enter the number between 0 and 10 and I will tell you your grade!");
while ((input=scanf("Your input:", &input) != EOF))
{
if (input < 0 || input > 10) //input is invalid
{
printf("Sorry, invalid character data.");
while (getchar() !='\n')
{
printf("Your input must be from 0 to 10.", input);
scanf("%d", &input); //This part looks very bad for me
}
}
else
switch (input)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your grade is F. \n");
break;
case 6:
printf("Your grade is D. \n");
break;
...
我的功课得到了这么远,这里有一些我无法抗拒的“剩余”问题。
1)每当用户在输入后提交任何内容时,它将进入无限循环并打印您的成绩为F ,即使案例= 6也是如此。
2)我在每个案例结尾处使用 break; 。看起来它们不起作用(?)
3)看起来像第二个循环中第二行的问题
scanf("%d", &input); //This part looks very bad for me
但是我猜这些脚本接受它是真的,因为包含开关的else语句开始工作,因为否则它将不会打印你的成绩是F.
答案 0 :(得分:0)
尝试以下代码。当我们有无效数据时,看看 flush_stream 正在做什么......
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void flush_stream();
void flush_stream() {
char c;
do {
c = getchar();
}
while (!isdigit(c) && c != '\n');
ungetc(c, stdin);
}
int main(void) {
const char *prompt = "Input please: ";
int input; // input from user
printf("Enter the number between 0 and 10 and I will tell you your grade!\n");
while(1) {
printf("%s", prompt);
int ret = scanf("%d", &input);
if(ret == 0) {
printf("Sorry, invalid character data, your input must be from 0 to 10.\n");
flush_stream();
continue;
}
if(ret > 0) {
if (input < 0 || input > 10) {
printf("Sorry, invalid character data, your input must be from 0 to 10.\n");
flush_stream();
continue;
}
switch (input) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
printf("Your grade is F. \n");
break;
case 6:
printf("Your grade is D. \n");
break;
}
}
}
}
答案 1 :(得分:-2)
您似乎使用scanf
和printf
错误。
输入数字:
scanf("%d", &input);
输出数字:
printf("%d\n", input);
在循环中,当输入非法时,为什么不只是continue
到下一个循环?
while (true) {
printf("input your grade here: ");
if (scanf("%d", &input) == EOF) {
break;
}
if (input < 0 || input > 10) {
printf("your input is illegal.\n");
continue;
}
switch (input) {
...
}
}