代码适用于每个if语句,除了第一个语句,如果语句为真,它继续创建一个无限循环"输入学生标记[0.00,100,00]:"并且"没有接受任何输入!"。
#include <stdio.h>
#define MIN 0
#define MAX 100
int getMark(void) {
int mark;
char ch;
int repeat = 1;
printf("Enter a student mark [0, 100] : ");
int r = scanf("%i%c", &mark, &ch);
if (r == 0) {
printf("**No input accepted!**\n");
}
else if (ch != '\n') {
printf("**Trailing characters!**\n");
}
else if (mark < MIN || mark > MAX) {
printf("**Out of range!**\n");
}
return mark;
}
int main() {
int mark;
do {
mark = getMark();
} while (mark != 0);
}
导致它循环的原因是什么?如何解决?
答案 0 :(得分:0)
1)如果您输入字符串或仅输入char值,则必须在使用前将其从输入流中删除。
#include <stdio.h>
#define MIN 0
#define MAX 100
int getMark(void) //Funtion for marks input
{
int mark;
char ch;
//int repeat = 1;
char c;
printf("Enter a student mark [0.00, 100,00] : ");
int r = scanf("%d %c", &mark, &ch);
if (r == 0) //Input begins with a letter
{
printf("**No input accepted!**\n");
}
else if(ch == '\n') //Input ends with a letter
{
printf("**Trailing characters!**\n");
}
else if( mark < MIN || mark > MAX) //Range
{
printf("**Out of range!**\n");
}
//Remove the previous string from the input stream
while ( (c = getchar()) != '\n' && c != EOF );
return mark;
}
int main()
{
int mark;
do
{
mark = getMark();
}while (mark != 0);
return 0;
}
<强>输出强>
Enter a student mark [0.00, 100,00] : -10 c
**Out of range!**
Enter a student mark [0.00, 100,00] : 101 b
**Out of range!**
Enter a student mark [0.00, 100,00] : 50 a
Enter a student mark [0.00, 100,00] : abcd
**No input accepted!**
Enter a student mark [0.00, 100,00] : 0 q
答案 1 :(得分:0)
问题在于,如果没有接受输入,变量标记将是未初始化的,并且可能是其他的0.你的while循环将永远继续而不更新标记。