Joshua
Joshua

Reputation: 136

double value cant read by fscanf in c

# include <stdio.h>
# include <io.h>
# include <stdlib.h>
int main(int argc,char *argv[]){
   FILE *tfptr;
    int accno;
    double balance;
    if((tfptr=fopen("trans.dat","w"))==NULL){ //check the file trans.dat existed or not
        printf("cannot open file. \n");
        exit(1);
    }
    fscanf(stdin,"%d%f",&accno,&balance);/* read from keyboard */
    fprintf(tfptr,"%d %f",accno,balance);/* write to file */
    fclose(tfptr); //close the file trans.dat
    if((tfptr=fopen("trans.dat","r"))==NULL){ //check the file trans.dat file existed or not
        printf("cannot open file. \n");
        exit(1);
    }
    fscanf(tfptr,"%d%f",&accno,&balance);/* read from file  */
    fprintf(stdout,"%d %f",accno,balance);/* write to screen */
    return 0;
}

output:

12  2.3
12   0.000000
--------------------------------
Process exited with return value 0
Press any key to continue . . .

Upvotes: 1

Views: 1405

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409206

The "%f" format behaves differently between scanf and printf.

For scanf (and family) "%f" reads into a float variable, not a double. If you want to read a double then you need the "%lf" format for scanf.

Upvotes: 3

Related Questions