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:
looks bad...
if i change in fscanf: %c to %f
the return is:
looks great, but the variable idade is always 0... :S
wtf i have to do?
%c
to%f
? – Jonathon Dec 11 '11 at 20:10fscanf()
; it will tell you whether it read all the values it was supposed to. Also, you run into a problem with the newline; the%c
on the second iteration will pick up the newline from the previous line. Generally, don't usefscanf()
; it is hard to use correctly. Usefgets()
andsscanf()
instead; much easier to control and get correct. – Jonathan Leffler Dec 11 '11 at 20:20feof
only returns a true value after it's tried reading past the end of a file, not once you've read up to the end of the file. It can cause loops to run 1 extra time - as it does for you if you look at the last 2 lines of your output. Consider checking the return value offscanf
instead. – AusCBloke Dec 11 '11 at 20:22