C语言读取文本文件中的科学数据

#include <stdio.h>
# include <math.h>
void main()
{
int i;
double keys[5];
{
FILE *fp;
fp = fopen("e:\\datainput.txt", "rt");
if (!fp){
printf("Can not open input file.\n");
exit(-1);
}
while ( !feof(fp) )
{
fscanf(fp, "%lf ", &keys[i++]);
printf("%lf",keys[i]);
}
close(fp);
}
我文本文档datainput.txt中的数据是这样的:n行*1列科学数据,
0.0000000e+00
9.9998333e-03
1.9998667e-02
2.9995500e-02
3.9989334e-02
可是总是输出不了任何东西。我是用CCs3.3编译的,但是都是C语言应该没有问题。是我的科学数据不应当以double形式输出吗?求大神!我试过用整数形式的数据,是可以输出结果的(把形式都改成int和%d)

  可以使用两种方法很方便的读取科学计数法文本并转化为浮点数,分别是sscanf和atof。

  参考代码是用VC2008实现的,因此分别变形为它们各自的宽字符版本:swscanf和_wtof。  

  必须要注意的是,使用sscanf读取科学计数法时,必须使用%lf,而不是%f。

CString str = _T("1.9626E+004 2.6789E+004");

{
double f1, f2;
swscanf(str, _T("%lf %lf"), &f1, &f2);
TRACE(_T("%f %f\r\n"), f1, f2);
}

{
TCHAR str1[1024], str2[1024];
swscanf(str, _T("%s %s"), str1, str2);

double f1 = _wtof(str1);
double f2 = _wtof(str2);
TRACE(_T("%f %f\r\n"), f1, f2);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-27
首先,i的初始值要赋值成0,i++的位置不对,会影响到后面的printf语句,然后请记住ccs的printf遇到\n才能完成输出,while循环修改一下:
i=0;
while ( !feof(fp) )
{
fscanf(fp, "%lf", &keys[i]);
printf("%lf\n",keys[i]);
i++;
}
第2个回答  推荐于2016-04-07
#include <stdio.h>
# include <math.h>
void main()
{
int i=0;
double keys[5];

FILE *fp;
fp = fopen("e:\\datainput.txt", "rt");
if (!fp){
    printf("Can not open input file.\n");
    return ;
}
while ( !feof(fp) )

    fscanf(fp, "%lf  ", &keys[i]);
printf("%e\n",keys[i]); //
i++;
}
fclose(fp);
}

追问

你好,我试了一下您的程序,但是输出第一个数据之后就完了,没有继续读取下面的数据?

追答

怎么会呢?是不是你的文档有问题?

fscanf是遇空格或者回车都会跳的,不必像楼下那样多此一举


如果还有问题试一下这个

#include <stdio.h>
int main()
{
int i=0;
double keys[5]; 
FILE *fp;
fp = fopen("datainput.txt", "r");
if (!fp)
{
printf("Can not open the file.\n");
return 1;
}
while(!feof(fp))

fscanf(fp, "%lf", &keys[i]);
printf("%e\n",keys[i++]);
}
fclose(fp);
return 0;
}

本回答被提问者采纳
第3个回答  2014-03-27
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i;
double keys[5];
FILE *fp;

fp = fopen("e:\\datainput.txt", "rt");
if (!fp){
printf("Can not open input file.\n");
exit(-1);
}

while ( !feof(fp) )
{
fscanf(fp,"%lf",&keys[i]);//先读数据
fscanf(fp," ");//再读数据后的空格
printf("%e\n",keys[i]);//显示科学基数用%e,双精度浮点小数改为%lf就可以了
i++;
}
close(fp);
system("pause");
return 0;
}
相似回答