当我运行此代码时:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static void flush_stdin(void)
{
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
}
static int scand(int *val, int min, int max)
{
char s[32], *p = NULL;
long x = 0;
if (fgets(s, sizeof s, stdin)) {
x = strtol(s, &p, 10);
if (strchr(p, '\n') == NULL) flush_stdin();
}
if (p == NULL || *p != '\n' || x < min || x > max) {
*val = 0;
return 0;
} else {
*val = (int)x;
return 1;
}
}
int main(void)
{
int x;
do {
printf("Number (1-10): \n");
} while (scand(&x, 1, 10) == 0);
printf("Number = %d\n", x);
return 0;
}
我粘贴以下文本:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
我给出这个输出:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Number (1-10):
Number (1-10):
Number (1-10):
printf("Number (1-10): \n");
为粘贴的每一行进行处理。
是否可以在返回之前吃掉(冲洗)整个文本scand()
以便只处理一个printf
?