0

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

39.546147  19.849505  Name  Last 

而且我不知道我有多少行。我想要的是逐行阅读文本并简单地保留这四个元素中的每一个分隔变量。(在这种情况下,有 2 个浮点数和 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
4

2 回答 2

1

您正在使用 fgets 读取一行文本,然后将其丢弃(因为您再次使用 fscanf 读取)。

考虑使用函数 feof,而不是调用 fgets 作为您的 while 循环保护。因此,循环保护将变为

while(!feof(file1))
于 2012-05-23T16:39:49.057 回答
1

代替

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;
}

OUTPUT(用于带有空行的输入文件)

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 块中应该有一个 continue (或等效的)。

我添加了继续说明。

带有 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
于 2012-05-23T16:49:10.597 回答