简体   繁体   English

读取并添加从C中的文件读取的整数

[英]Reading and adding integers read from a file in C

So I've read a lot of similar posts but I can't nail down what my issue is here. 所以我读过很多类似的文章,但是我无法确定我的问题在这里。

{
    FILE * fp;
    fp = fopen("integer_store.txt", "r");

    int total;
    int i;

    clock_t start, end;
    double time;

    start = clock();

    fscanf(fp, "%d", &i);

    while(!feof(fp)) {

        fscanf(fp, "%d", &i);
        total = total + i;

    }

    end = clock();
    time = ((double)(end-start)) / CLOCKS_PER_SEC;

    printf("Total: %d\n",total);
    printf("Execution time: %f seconds \n",time);
    fclose(fp);

}

The goal is to print a total of all the numbers in a file of ASCII numbers separated by spaces... everything seems to work except every time I run it i get a different total for the same file. 目标是将所有数字的总和打印在一个用空格分隔的ASCII数字文件中……一切似乎都可以正常工作,除了每次运行它时,对于同一个文件我都会得到不同的总数。

Please initialize the variable total like int total = 0; 请初始化变量total例如int total = 0; first. 第一。

Moreover, you should check if fopen succeeded ( fp is not NULL ). 此外,您应该检查fopen成功( fp不是NULL )。

您永远不会初始化total所以您要增加随机内存。

total is not initialized to 0. total未初始化为0。

Try this declaration: 试试这个声明:

int total = 0;

Just to add to the explanation, in C and C++, any variable that has not been initialized DOES actually have a value, and that value is random. 只是为了补充说明,在C和C ++中,任何尚未初始化的变量DOES实际上都有一个值,并且该值是随机的。 This is why every time you ran the program, you would get a different result. 这就是为什么每次运行该程序都会得到不同的结果的原因。

Check this out if you want more of an explanation: https://en.wikipedia.org/wiki/Uninitialized_variable 如果需要更多说明,请查看此: https : //en.wikipedia.org/wiki/Uninitialized_variable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM