我有一个函数可以从 C 中的 stdin
获取数字。
int io_get_num(const char *q, const size_t min, const size_t max, int * num)
{ /* Get a number from the command line */
int ret = 0;
do {
printf(q);
ret = scanf(" %d", num);
if (ret == EOF)
return EOF;
else if (ret == 0)
printf("Please provide a valid number ..\n%s", q);
else if (*num > max || *num < min)
printf("Number must be smaller than %u and larger than %u\n%s", (unsigned int)max+1, (unsigned int)min-1, q);
else
break;
/* Flushing stdin */
int ch;
while ( (ch = fgetc(stdin)) != EOF && ch != '\n' );
} while (1);
return ret;
}
它在第一次循环运行中工作正常,之后(我在使用 gdb 中断时注意到)循环运行两次,除了它不等待我的输入或检查任何条件(这可能与刷新有关)流)..
对于这个问题我能做什么?
最佳答案
出于某种原因,每次迭代都会打印 q
两次:一次在开始处,然后在错误消息之后再次打印。这可能会产生每个输入循环迭代两次的错觉,而实际上它不会发生。在我的实验中,我无法重现这种双重迭代。
此外,scanf("%d", num)
中 %d
之前的空格是多余的。这不是一个错误,它会让 scanf
跳过任何前导空格,但 %d
已经在内部自行跳过了前导空格。
关于c - 从 C 中的 stdin 读取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26263435/