以下更新
我需要测试输入是否为整数,如果是,则继续执行某些操作。
如果输入不是整数,我需要打印错误信息并退出。
我使用的方法是scanf
将返回读取项目的数量,在我的情况下我希望它返回1.所以我测试scanf
是否返回1,并执行我的其他代码。
但是,出于某种原因scanf
没有返回1
我遇到了无限循环
代码:
/*
* Read in a number of values to read and then print the average
* of those values.
*/
#include <stdio.h>
#include "tfdef.h"
#define DEBUGGING 1;
int main() {
int expected;
int count;
double sum;
int value;
int flag;
while (flag = scanf("%d", &expected) != EOF) {
#ifdef DEBUGGING
printf("flag: %d expected: %d\n", flag, expected);
#endif
if (flag == 1) {
sum = 0;
for (count = 0; count < expected; count++) {
scanf("%d", &value);
sum += value;
}
printf("Average of %d values is %.2f\n",
count, count != 0 ? sum / count : 0.0);
} else {
printf("Error! Can't read number of expected values.\n");
}
}
}
更新
以下代码似乎有效,除了初始输入是数字后跟字母的情况。例如:
输入:eeee33333
印刷:Error! Can't read number of expected values.
输入:333eeee
印刷:Debug1 flag:1 expected: 333
代码
#include <stdio.h>
#include "tfdef.h"
#define DEBUGGING 1;
int main() {
int expected;
int count;
double sum;
int value;
int flag;
while (flag = scanf("%d", &expected)) {
#ifdef DEBUGGING
printf("Debug1 flag: %d expected: %d\n", flag, expected);
#endif
if (flag == EOF) {
#ifdef DEBUGGING
printf("Debug2 flag: %d expected: %d\n", flag, expected);
#endif
return 0;
}
while (getchar() != '\n');
if (flag == 1) {
sum = 0;
for (count = 0; count < expected; count++) {
scanf("%d", &value);
sum += value;
}
printf("Average of %d values is %.2f\n",
count, count != 0 ? sum / count : 0.0);
}
}
printf("Error! Can't read number of expected values.\n");
}
答案 0 :(得分:1)
此问题的最佳解决方案是使用fgets()
读取输入并使用sscanf()
进行解析,但是获得无限循环的原因是:您的测试不正确:
while (flag = scanf("%d", &expected) != EOF)
flag
收到scanf
和EOF
的返回值之间的比较结果......您可能想要写这个:
while ((flag = scanf("%d", &expected)) != EOF)
但是如果用户键入了无法解析为int
的内容,则此类输入会在stdin
缓冲区中徘徊,而scanf()
会继续尝试解析它。
尝试这种方法:
#include <stdio.h>
int getnumber(int *valp) {
char line[80];
char last;
while (fgets(line, sizeof line, stdin)) {
flag = sscanf(line, "%d %c", &expected, &last);
if (flag < 1) {
printf("Input is not a number: %s", line);
continue;
}
if (flag > 1) {
printf("Extra characters after number input: %s", line);
continue;
}
return 0;
}
return EOF;
}
int main(void) {
int expected;
int count;
double sum;
int value;
while (getnumber(&expected) != EOF) {
sum = 0;
for (count = 0; count < expected; count++) {
if (getnumber(&value) == EOF) {
printf("Error! Can't read number of expected values.\n");
break;
}
sum += value;
}
printf("Average of %d values is %.2f\n",
count, count != 0 ? sum / count : 0.0);
}
return 0;
}