Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read from .txt C

Tags:

c

scanf

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?

like image 427
Shermano Avatar asked Jan 24 '26 10:01

Shermano


1 Answers

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.

like image 186
schnaader Avatar answered Jan 26 '26 00:01

schnaader