尝试对文本文件中的值求和,接收无法识别的字符作为输出?

Trying to sum values from a text file, receiving unrecognized character as output?

我正在使用 C 尝试对文件中的数字求和。该文件包含数字,例如:

123
456
788
...
356

当 运行 代码时,它正确地要求输入并打印我输入的数字。但是,它不会对文件求和,只会显示一个无法识别的字符符号,例如一个小的 ?。我认为人数没有超过分配的 INT_MAX_SIZE。似乎是什么问题?

#include <stdio.h>

main() {

    //Number variable to assign each line to 
    int c;
    int fds[2];
    int childid;
    int size;
    int number;
    int sum;

    printf ("Enter the number of processes to create: ");
    scanf ("%d", &number);
    printf ("You entered: %d", number);
    printf("\n");

    //File I/O operations
    FILE *file;

    //Open file for reading
    file = fopen("Project1_OS/project1_data/file1.dat", "r");

    //If file is found
    if (file) {
        //While file has data to be read
        while ((c = getc(file)) != EOF)
            //Print data
           //putchar(c);
            sum+=c;         


    //Close the file I/O
    fclose(file);
    }
    putchar(sum);

}

首先getc它是一个从文件中读取字符而不是整数的函数。 你必须使用 fscanf :

fscanf(file,"%3d",&c)

second putchar 这是一个打印字符而不是整数的函数。 所以你必须写:

printf("%d",sum);