gpt4 book ai didi

c - 用于在 switch 语句之前刷新数据的双 while 循环

转载 作者:行者123 更新时间:2023-11-30 18:15:15 25 4
gpt4 key购买 nike

我需要编写一个脚本,让用户输入 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) 每当用户在输入后提交任何内容时,它都会进入无限循环并打印 Your Grade is F.,即使 case = 6 时也是如此。

2)我在每个案例的末尾使用了break;。看起来它们不起作用(?)

3)看起来问题出在第二个循环的第二行

scanf("%d", &input); //This part looks very bad for me

但我猜脚本会接受它为 true,因为包含 switch 的 else 语句开始起作用,否则它不会打印 Your Grade is F.

最佳答案

尝试以下代码。看看当我们有无效数据时 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;
}
}
}
}

关于c - 用于在 switch 语句之前刷新数据的双 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36145097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com