2

Hi i have this text file, where the first column in a character the 2nd and the third one is an integer.. but I'm not able to read and print the values correctley.

So this the file am trying to read:

c 6
o 4 3
o 2 4
o 3 2
o 1 1
o 3 3

And here is the code :

#include <stdio.h>
#include <stdlib.h>

#define N 6

int main (int argc, char *argv[]) 
{
  int i;
  int M[N];
  int U[N];
  char c ;
  FILE* fichier = NULL;

  fichier = fopen("pb1.txt","r");

if(fichier!= NULL )
  { 
    while(!feof(fichier))   
    {
    fscanf(fichier, "%c %d %d", &c, &M[i], &U[i]); 

    printf("%c %d %d \n", c, M[i],U[i]);
    }

  }
}

This is what the output looks like

c 6 1472131424 
o 4 3 

 4 3 
o 2 4 

 2 4 
o 3 2 

 3 2 
o 1 1 

 1 1 
o 3 3 

 3 3 

I have no clue why it gives me this. thank you

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
MongJi
  • 117
  • 2
  • 6
  • 1
    Welcome to Stack Overflow! Please see [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/q/5431941/2173917) – Sourav Ghosh Nov 09 '16 at 15:26

1 Answers1

1

The first problem I see here, is you use the value of i uninitialized. It invokes undefined behavior.

To elaborate, i is an automatic local variable and unless intialized explicitly, will have an indeterminate value. Attempt to use that will lead to UB.

Also, you have never increased the value of i which is supposed to be used as the index for storing and printing the values.

Lastly, always check the return value of scanf() and family to ensure the success, before you try to use the scanned value.

That said, Please see Why is “while ( !feof (file) )” always wrong?

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261