gpt4 book ai didi

c - 在C中逐行读取并识别元素

转载 作者:行者123 更新时间:2023-11-30 14:25:06 24 4
gpt4 key购买 nike

我有一个文件,其行就是这种形式。

39.546147  19.849505  Name  Last 

而且我不知道我有多少行。我想要的是逐行读取文本,并简单地保留这 4 个元素中的每个元素的分隔变量。 (在这种情况下,有 2 个 float 和 2 个字符串 -char[]。)

到目前为止我的代码是这样的:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE * file1;

file1 = fopen("args.txt","r");
float var0;
float var1;
char S1 [128];
char S2 [128];
int assignments;

if ( file1 != NULL ){
char line [ 256 ];
while ( fgets ( line, sizeof line, file1 ) != NULL ) //read a line
{
//printf("%s\n",line);
assignments = fscanf( file1, "%f %f %s %s",&var0, &var1, &S1, &S2 );
if( assignments < 4 ){
fprintf( stderr, "Oops: only %d fields read\n", assignments );
}
printf("%f --- %f ---- %s ---- %s \n",var0, var1,S1,S2);
}
fclose ( file1 );

}
else {
perror ( "args.txt" ); /* why didn't the file open? */
}
return 0;
}

我得到的结果是它只读取一个元素。你能帮我解决这个问题吗?

args.txt 示例

39.546147  19.849505  george  papad 

39.502277 19.923813 nick perry

39.475508 19.934671 john derrick

最佳答案

替换

assignments = fscanf( file1, "%f %f %s %s",&var0, &var1, &S1, &S2 );

assignments = sscanf( line, "%f %f %s %s",&var0, &var1, &S1, &S2 );

更新:下面的程序在这里工作。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
FILE * file1;

float var0;
float var1;
char S1 [128];
char S2 [128];
char line [ 256 ];
int assignments;

file1 = fopen("args.txt","r");

if ( file1 == NULL ){
perror ( "args.txt" ); /* why didn't the file open? */
return 1;
}

while ( fgets ( line, sizeof line, file1 ) != NULL ) //read a line
{
//printf("%s\n",line);
assignments = sscanf( line, "%f %f %s %s",&var0, &var1, S1, S2 );
if( assignments < 4 ){
fprintf( stderr, "Oops: only %d fields read\n", assignments );
continue; /* <<----- */
}
printf("%f --- %f ---- %s ---- %s \n",var0, var1,S1,S2);
}
fclose ( file1 );

return 0;
}

输出(对于带有空行的输入文件)

39.546146 --- 19.849504 ---- george ---- papad  
Oops: only -1 fields read
39.546146 --- 19.849504 ---- george ---- papad
39.502277 --- 19.923813 ---- nick ---- perry
Oops: only -1 fields read
39.502277 --- 19.923813 ---- nick ---- perry
39.475510 --- 19.934671 ---- john ---- derrick

这是预期的,oops block 中应该有一个 continue (或等效的)。

我添加了继续说明。

程序的输出与继续:

39.546146 --- 19.849504 ---- george ---- papad  
Oops: only -1 fields read
39.502277 --- 19.923813 ---- nick ---- perry
Oops: only -1 fields read
39.475510 --- 19.934671 ---- john ---- derrick

关于c - 在C中逐行读取并识别元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10724187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com