1

我需要我的程序读取文件的一行,然后解析该行并将任何单词插入每个数组的索引中。唯一的问题是我不知道每行有多少个单词,每行可以是1-6个单词。

所以这就是一个简单文件的样子:

苹果橘子

电脑终端键盘鼠标

如果我正在扫描第 1 行,我需要一个 char 数组来保存单词 apple 和 oranges。例如:

words[0][0] = "apple";
words[1][0] = "oranges";

到目前为止,我有这样的东西,但我怎样才能让它每行少于 6 个单词?

fscanf(file, "%19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ]", string1, string2, string3, string4, string5, string6);
4

1 回答 1

-1

您正在阅读整个文件,而不是一行。

你可以这样做:

char line [128];
char *pch;
char words[6][20]; // 6 words, 20 characters 
int x;

while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
         pch = strtok (line," ,.-");
         while (pch != NULL)
         {
            strcpy(words[x], pch);
            pch = strtok (NULL, " ,.-");
         }
         x++;

        /*
           At this point, the array "words" has all the words in the line
         */

      }
于 2013-10-29T17:54:00.247 回答