fopen fscanf 读取文件,该如何解决
fopen fscanf 读取文件
我有一个TXT 文件
608196.63, 107311.12, 2.63
608196.63, 107311.11, 2.62
608196.63 ,107311.11, 2.61
我用fopen fscanf 读取 ,代码如下
没有任何问题!1
但是我换个文件 使用空格分开,如
608196.63 107311.12 2.63
608196.63 107311.11 2.62
608196.63 107311.11 2.61
然后我把上句换成
fscanf(file,"%Lf %Lf %Lf %d %d %d %f %s\n",&tempPt.x,&tempPt.y,&tempPt.z,&tempPt.r,&tempPt.g,&tempPt.b,&tempPt.i,&tempPt.c);
然后就读取错误
tempPt.x=608196.63
tempPt.y= 107311.12
tempPt.z=2.629999999999
tempPt.r=608196 //*************错误
tempPt.g=0
奇怪,我到底哪里错了我?????
------解决思路----------------------

我有一个TXT 文件
608196.63, 107311.12, 2.63
608196.63, 107311.11, 2.62
608196.63 ,107311.11, 2.61
我用fopen fscanf 读取 ,代码如下
string FileName="D:\\******tt.txt";
FILE * file=fopen(FileName.c_str(),"r");
if(file==NULL)
{
return;
}
long i=0;
while(!feof(file))
{
IPoint tempPt;
tempPt.b=0;
tempPt.c=0;
tempPt.i=0;
tempPt.r=0;
tempPt.x=0;
tempPt.y=0;
tempPt.z=0;
tempPt.g=0;
fscanf(file,"%Lf, %Lf ,%Lf ,%d ,%d, %d, %f, %s\n",&tempPt.x,&tempPt.y,&tempPt.z,&tempPt.r,&tempPt.g,&tempPt.b,&tempPt.i,&tempPt.c);
if(tempPt.x!=0&&tempPt.y!=0)
{
double a=tempPt.x;
double b=tempPt.y;
}
}
fclose(file);
没有任何问题!1
但是我换个文件 使用空格分开,如
608196.63 107311.12 2.63
608196.63 107311.11 2.62
608196.63 107311.11 2.61
然后我把上句换成
fscanf(file,"%Lf %Lf %Lf %d %d %d %f %s\n",&tempPt.x,&tempPt.y,&tempPt.z,&tempPt.r,&tempPt.g,&tempPt.b,&tempPt.i,&tempPt.c);
然后就读取错误
tempPt.x=608196.63
tempPt.y= 107311.12
tempPt.z=2.629999999999
tempPt.r=608196 //*************错误
tempPt.g=0
奇怪,我到底哪里错了我?????
------解决思路----------------------
FILE * file=fopen(FileName.c_str(),"r");
if (file==NULL) return;
long i=0;
char ln[1000];
while (1) {
if (NULL==fgets(ln,1000,file)) break;
if ('\n'==ln[strlen(ln)-1]) ln[strlen(ln)-1]=0;
IPoint tempPt;
tempPt.b=0;
tempPt.c=0;
tempPt.i=0;
tempPt.r=0;
tempPt.x=0;
tempPt.y=0;
tempPt.z=0;
tempPt.g=0;
if (8==sscanf(ln,
"%lf%*[^0-9]"
"%lf%*[^0-9]"
"%lf%*[^0-9]"
"%d%*[^0-9]"
"%d%*[^0-9]"
"%d%*[^0-9]"
"%f,"
"%s"
,&tempPt.x
,&tempPt.y
,&tempPt.z
,&tempPt.r
,&tempPt.g
,&tempPt.b
,&tempPt.i
, tempPt.c
)) {
printf("Line %ld: %lg %lg %lg %d %d %d %s\n"
,i+1
, tempPt.x
, tempPt.y
, tempPt.z
, tempPt.r
, tempPt.g
, tempPt.b
, tempPt.i
, tempPt.c
);
if(tempPt.x!=0.0&&tempPt.y!=0.0) {
double a=tempPt.x;
double b=tempPt.y;
}
} else {
printf("Line %ld format error:%s\n",i+1,ln);
getchar();
}
i++;
}
fclose(file);