C语言读取文本文件浮点数。

2025-05-14 17:55:46
推荐回答(4个)
回答(1):

#include 
#include 
#include 

#define MAXLEN 20

int main () {
FILE *fp;
int ch,i = 0,n = 0;
char str[MAXLEN],filename[] = "indata.txt";
if((fp = fopen(filename,"rt")) == NULL) {
printf("不能打开文件:%s\n",filename);
return 1;
}
while((ch = fgetc(fp)) != EOF) {
if(ch == '\t' || ch == '\n') {
if(i > 0) {
str[i++] = '\0';
printf("%g\n",atof(str));
i = 0;
++n;
}
}
else str[i++] = ch;
}
printf("有效数据个数:%d\n",n);
fclose(fp);
return 0;
}

回答(2):

  1. 使用文本操作函数fscanf读入即可。

  2. 核心代码:

    float a;
    FILE * f=fopen("文本名称","r");
    fscanf(f,"%f",&a);
    fclose(f);

回答(3):

#include
FILE *fp = fopen("TXT文件路径", "r");
double dbTmp;
while (!feof(fp))
{
fscanf(fp, "%lf", &dbTmp); //读出的数在dbTmp里,一次读一行。
}
fclose(fp); //读完就退出循环

回答(4):

fscanf(xxx," %lf",&xxx);