0

Problem: The issue I'm having is that I have a file with 20 integers, and all I'm trying to do is have those 20 integers read. Which occurs in this program... except that there's an additional value inserted at the start, which is whatever int num; is initialized as. Even if I remove initialization, I'm given a default integer value of 3739648.

How can I remedy this?

int main() {
    FILE* fp = fopen("20integers.txt", "r");
    int num =0;

    fseek(fp, 0, SEEK_SET);

    if(fp == NULL) {
        return 1;
    }
    //fseek(fp, 5, SEEK_SET);
    while (!feof (fp))
    {
        printf ("%d ", num);
        fscanf (fp, "%d", &num);
    }

    fclose (fp);
    return 0;
}

Output:

0 1 20 17 1 14 12 9 88 61 16 7 11 7 6 31 47 3 47 18 2
Process finished with exit code 0

The first '0' should not be there.

hellow
  • 12,430
  • 7
  • 56
  • 79
J Ben
  • 127
  • 9

2 Answers2

1
  • You must read the integer before printing it
  • You really should test the return of fscanf function, and exit the loop if conversion failed:


while (1)
{
    if (1 != fscanf (fp, "%d", &num))
        break;

    printf ("%d ", num);
}
Mathieu
  • 8,840
  • 7
  • 32
  • 45
0

I think what you are trying to say is that you are getting an extra value at the start from your explanation. This is because you are calling printf ("%d ", num) before fscanf (fp, "%d", &num);

make your while loop like

while (!feof (fp))
   {
      fscanf (fp, "%d", &num);
      printf ("%d ", num);
   }

hopefully your problem will be solved :)

Farrukh
  • 153
  • 1
  • 8
  • 1
    *hopefully your problem will be solved* No, it won't be. Read: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Andrew Henle Oct 18 '18 at 14:33
  • 1
    In respect to the question asked i think it will. no offence though – Farrukh Oct 18 '18 at 14:44