我只是想问为什么我的功能read_int
不接受fgetc
作为int
的输入? (我认为是这种情况,因为我总是输入一个整数但它仍然会转到显示错误的int
函数。
这是我的代码(来自我的教授的skel代码):
int main() {
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;
}
int read_int(void) {
int f = fgetc(stdin);
if (fgetc(stdin) != EOF) {
printf("Sorry that is invalid.");
exit(1);
}
return f;
}
答案 0 :(得分:2)
fgetc()
用于从流中读取字节,它一次返回一个字符。
要阅读int
,请使用scanf("%d", &f)
并阅读double
,scanf("%lf", &d)
f
和d
定义为{{1}分别和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