我知道这是一个愚蠢的问题,但是如何从多行文本文件中加载数据?

while (!feof(in)) {
    fscanf(in,"%s %s %s \n",string1,string2,string3);
}


^^这是我从一行加载数据的方式,并且工作正常。我只是不知道如何从第二行和第三行加载相同的数据。

再一次,我意识到这可能是一个愚蠢的问题。

编辑:问题没有解决。我不知道如何从不在第一行的文件中读取文本。我该怎么做?很抱歉这个愚蠢的问题。

最佳答案

尝试类似的方法:

/编辑/

char line[512]; // or however large you think these lines will be

in = fopen ("multilinefile.txt", "rt");  /* open the file for reading */
/* "rt" means open the file for reading text */
int cur_line = 0;
while(fgets(line, 512, in) != NULL) {
     if (cur_line == 2) { // 3rd line
     /* get a line, up to 512 chars from in.  done if NULL */
     sscanf (line, "%s %s %s \n",string1,string2,string3);
     // now you should store or manipulate those strings

     break;
     }
     cur_line++;
}
fclose(in);  /* close the file */


甚至...

char line[512];
in = fopen ("multilinefile.txt", "rt");  /* open the file for reading */
fgets(line, 512, in); // throw out line one

fgets(line, 512, in); // on line 2
sscanf (line, "%s %s %s \n",string1,string2,string3); // line 2 is loaded into 'line'
// do stuff with line 2

fgets(line, 512, in); // on line 3
sscanf (line, "%s %s %s \n",string1,string2,string3); // line 3 is loaded into 'line'
// do stuff with line 3

fclose(in); // close file

关于c - C,读取多行文本文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5827931/

10-11 22:12
查看更多