fgetc() 用于从流中读取字节,一次返回一个字符。
要读取int,使用scanf("%d", &f),读取double、scanf("%lf", &d),f和d分别定义为int f;和double d;。
还包括<stdio.h> 并在调用它们之前定义函数。
这是修改后的版本:
#include <stdio.h>
int read_int(void) {
int f;
if (scanf("%d", &f) != 1) {
printf("Sorry that input is invalid.\n");
exit(1);
}
return f;
}
double read_double(void) {
double d;
if (scanf("%lf", &d) != 1) {
printf("Sorry that input is invalid.\n");
exit(1);
}
return d;
}
int main(void) {
int the_int;
double the_double;
printf("Doing tests of read_int and read_double functions ...\n\n");
printf("Please try to enter an int: ");
the_int = read_int();
printf("read_int succeeded. It read a value of %d.\n", the_int);
printf("Please try to enter a double: ");
the_double = read_double();
printf("read_double succeeded. It read a value of %g.\n", the_double);
return 0;
}
如果您需要使用fgetc() 来读取输入流,这里是read_int 和read_double 的修改版本,用于将这些字节转换为实际数字:
#include <stdlib.h>
int read_int(void) {
int c;
int sign = 1;
int f = 0;
/* skip leading white space */
while ((c = fgetc(stdin)) == ' ' || c == '\n')
continue;
/* handle optional sign */
if (c == '-') {
sign = -1;
c = fgetc(stdin);
} else
if (c == '+') {
c = fgetc(stdin);
}
/* convert digits */
if (c >= '0' && c <= '9') {
f = c - '0';
while ((c = fgetc(stdin)) >= '0' && c <= '9')
f = f * 10 + c - '0';
if (c != EOF)
ungetc(c, stdin);
} else {
/* no digits: fatal error */
if (c == EOF)
printf("Unexpected end of file\n");
else
printf("Sorry that input is invalid: %c\n", c);
exit(1);
}
/* apply sign and return value */
return sign * f;
}
double read_double(void) {
char buf[80];
int c;
size_t pos = 0;
double d;
char *p;
/* read a line of input */
while (pos < sizeof(buf) - 1 && (c = fgetc(stdin)) != EOF && c != '\n')
buf[pos++] = c;
buf[pos] = '\0';
/* use standard library function to convert the number */
p = buf;
d = strtod(buf, &p);
/* if conversion failed, report fatal error */
if (p == buf) {
printf("Sorry this input is invalid: %s\n", buf);
exit(1);
}
return d;
}