fscanf在c中读取的双值不能读

时间:2015-04-24 16:21:16

标签: c scanf

# 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;
}

输出:

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

1 个答案:

答案 0 :(得分:3)

"%f"格式在scanfprintf之间的行为有所不同。

对于scanf(和家人)"%f",会读入float变量,而不是double。如果您想阅读double,那么"%lf"需要scanf格式。