[英]Reading values from a text file?
I have data in a text file in the following format我有以下格式的文本文件中的数据
WA5362288SeaTac city 25496 10176 434224 9.964121 0.167655 47.441406-122.293077
WA5363000Seattle city 563374 270524 151956998 83.872647 58.670927 47.626353-122.333144
Now I am trying to extract specific values from the above data (which has had some padding spaces removed), for example现在我试图从上面的数据中提取特定的值(删除了一些填充空格),例如
WA SeaTAC 47.441406 -122.293077
I am unsure of how to get values from specific columns in C while streaming through a text file我不确定如何在通过文本文件流式传输时从 C 中的特定列中获取值
FILE *fp;
fp = fopen("places.txt", "r");
if(fp == NULL){
fprintf(stderr, "Can't open the file");
exit(1);
}
while(!feof(fp)){
//extract values from specific column
//fscanf()
}
I have assumed your file contains the following :我假设您的文件包含以下内容:
WA 5362288 SeaTac city 25496 10176 434224 9.964121 0.167655 47.441406 -122.293077
WA 5363000 Seattle city 563374 270524 151956998 83.872647 58.670927 47.626353 -122.333144
Let the file name is simple.txt .让文件名是 simple.txt 。 Then the following code meets your purpose :
然后以下代码符合您的目的:
#include <stdio.h>
FILE *fp;
int main()
{
char buff1[80],buff2[80];
char buff3[80];
int num,num1,num2,num3 ;
float num4,num5,num6,num7;
fp = fopen("simple.txt", "r");
if(fp == NULL){
fprintf(stderr, "Can't open the file");
exit(1);
}
while(fscanf(fp, "%19s %d %19s %19s %d %d %D %f %f %f %f ", buff1,&num,buff2,buff3,&num1,&num2,&num3,&num4,&num5,&num6,&num7)!= EOF)
printf("%s %d %s %s %d %d %d %f %f %f %f \n",buff1,num,buff2,buff3,num1,num2,num3 ,num4,num5,num6,num7);
fclose(fp);
}
This code prints the contents of file as shown below :此代码打印文件的内容,如下所示:
WA 5362288 SeaTac city 25496 10176 434224 9.964121 0.167655 47.441406 -122.293076
WA 5363000 Seattle city 563374 270524 151956998 83.872650 58.670925 47.626354 -122.333145
Hope this helps .希望这可以帮助 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.