0

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.

owacoder
  • 4,815
  • 20
  • 47
kang
  • 89
  • 10
  • 1
    Also, [Change `fscanf(fp, "%d", &i); while(!feof(fp)) { fscanf(fp, "%d", &i); /* ... */ }` to `while(fscanf(fp, "%d", &i) == 1) { /* ... */ }`](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Spikatrix Sep 21 '15 at 03:26

4 Answers4

4

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

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

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
2

You never initialize total so you are incrementing random memory.

Michael Albers
  • 3,721
  • 3
  • 21
  • 32
2

total is not initialized to 0.

Try this declaration:

int total = 0;
owacoder
  • 4,815
  • 20
  • 47
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

starblazer
  • 46
  • 2