使用fgetc和stdin指针。错误处理输入

时间:2018-05-26 15:24:10

标签: c

我只是想问为什么我的功能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;
}

1 个答案:

答案 0 :(得分:2)

fgetc()用于从流中读取字节,它一次返回一个字符。

要阅读int,请使用scanf("%d", &f)并阅读doublescanf("%lf", &d) fd定义为{{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