简体   繁体   中英

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.

Please initialize the variable total like int total = 0; first.

Moreover, you should check if fopen succeeded ( fp is not NULL ).

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

total is not initialized to 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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