Shermano
Shermano

Reputation: 1150

read from .txt C

I'm having some trouble with C language..

I have one file txt with various lines in the form:

F   65  S   4   1   139.56  3704.26

and my program:

p = fopen("dados.txt", "r");

if ( p == NULL) {
    printf("\n\nNao foi possivel abrir o arquivo.\n");
    exit(1);
}else{
      while ( !feof(p) ){
      fscanf(p,"%c %d %c %d %d %f %f",
          &sexo,&idade,&estadoCivil,&numFilhos,&freq,&mediaGasto,&mediaSalarial);

      printf("%c %d %c %d %d %f %f\n",
          sexo,idade,estadoCivil,numFilhos,freq,mediaGasto,mediaSalarial);
      }

the return is:

enter image description here

looks bad...

if i change in fscanf: %c to %f

the return is:

enter image description here

looks great, but the variable idade is always 0... :S

wtf i have to do?

Upvotes: 3

Views: 1321

Answers (1)

schnaader
schnaader

Reputation: 49719

You have to add the newline to your scanf call:

  fscanf(p,"%c %d %c %d %d %f %f\n",
      &sexo,&idade,&estadoCivil,&numFilhos,&freq,&mediaGasto,&mediaSalarial);

Without the newline in scanf, the first line will be correct, but the following line assigns the newline from the input to sexo.

Upvotes: 4

Related Questions