我有一个看起来像这样的文本文件:
;3;untyped;31.1948;29.917
;3;untyped;31.195;29.9168
;3;untyped;31.195;3;29.9167
;3;untyped;31.1955;29.9166
我想将其复制到另一个文本文件中,如下所示:
number_of_lines lat1 long1 t1 lat2 long2 t2 lat3 long3 t3.....
其中t从1开始,每次递增1。
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *file2 = fopen("out.txt", "w");
int NOL=1;
char ch;
FILE *file1 = fopen("in.txt", "r");
while((ch=fgetc(file1))!=EOF) //loop to find out how many lines are in the text file
{
if (ch=='\n') { NOL++; }
}
printf("number of lines = %d \n",NOL);
fclose(file1);
char line[100];
int inc = 1;
FILE *file3 = fopen("in.txt", "r");
fprintf(file2,"%d ",NOL);
for(int i=0;i<NOL;i++)
{
fscanf(file3,"%s\n",line);
char *trash1 = strtok(line, ";"); //ignoring the first part
printf("%s\n",trash1);
char *trash2 = strtok(NULL, ";"); //ignoring the second part
printf("%s\n",trash2);
char *lat = strtok(NULL, ";");
float lat_f = atof(lat); //storing the lat
printf("%s\n",lat);
char *lon = strtok(NULL, ";");
float lon_f = atof(lon); //storing the long
printf("%s\n",lon);
fprintf(file2,"%f %f %d ",lat_f,lon_f,inc); //printing the values to the output text file
inc++;
}
fclose (file3);
fclose (file2);
}
当我运行我的代码时,一些复制的值没有被正确复制,如下所示
4 31.194799 29.917000 1 31.195000 29.916800 2 31.195000 **3.000000** 3 31.195499 29.916599 4
为什么会这样?代码有问题吗?我该怎么办呢。
答案 0 :(得分:1)
您的第三行有一个可选的;
,因此输出正确
答案 1 :(得分:1)
在您的示例4行中,第3行包含字段4 3;
中的其他数据,以便您的&#34;意外&#34; 3
来自。{/ p>