-1

I cant get my if statement to actually print anything even when it should be true.

When I remove the if statement the program runs through the while loop until the end of the text file, however it will stop once the if statement condition is met. (I have the problematic if statement commented out for the sake of posting this)

#include <stdio.h>
int *file_int, *file_int2, *inv1,*inv2, *inv3, *inv4, *num;
int counter = 0;

int main(){
    FILE * in_file;
    in_file = fopen("beerinput.txt", "r");
    while (!feof(in_file)){
        counter +=1;
        printf("LOOP #%d\n", counter);
        fscanf(in_file, "%d\n", &file_int);
        printf("file_int = %d\n", file_int);

        fscanf(in_file, "%d\n", &file_int2);
        printf("file_int2 = %d\n", file_int2);
      /*if (file_int == 1){
            inv1 += *file_int2;
            printf("%d", inv1);
        }
        else{
        continue;
        }
        */
}
}

Output when if statement is commented out:

LOOP #1
file_int = 100
file_int2 = 300
LOOP #2
file_int = 500
file_int2 = 900
LOOP #3
file_int = 1
file_int2 = 200
LOOP #4
file_int = 2
file_int2 = 200
LOOP #5
file_int = 3
file_int2 = -100
LOOP #6
file_int = 4
file_int2 = 200
LOOP #7
file_int = 4
file_int2 = -200
LOOP #8
file_int = 3
file_int2 = -100
LOOP #9
file_int = 2
file_int2 = -300
LOOP #10
file_int = 1
file_int2 = -99
LOOP #11
file_int = -1
file_int2 = -99

VS. Output when the if statement isnt commented out:

LOOP #1
file_int = 100
file_int2 = 300
LOOP #2
file_int = 500
file_int2 = 900
LOOP #3
file_int = 1
file_int2 = 200
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
da randy
  • 29
  • 4
  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong?r=SearchResults&s=1|275.2640 – Yunnosch Jul 25 '19 at 23:03
  • 1
    Your problems start here: `fscanf(in_file, "%d\n", &file_int);`. `fscanf` expects a pointer to `int`, but you pass a pointer to pointer to `int`. *Please* turn on your compiler warnings. It should've told you about this problem right away. And `printf("file_int = %d\n", file_int);` is likewise incorrect. – HolyBlackCat Jul 25 '19 at 23:09

1 Answers1

-1

I expect your code is crashing when you execute the commented out line.

file_int2 is an integer. *file_int2 is a pointer to random piece of memory, and you are likely crashing your program when trying to access it. Apparently your computer is happy to let you access memory at small addresses, but not small negative addresses.

Likewise, inv1 has never been initialized. I think you're trying to write int inv1 = 0; // initialization at the top inv1 += file_int2; // add integer