C 把单词排成一行,排成一行

C 把单词排成一行,排成一行,c,scanf,C,Scanf,我需要我的程序读取文件的一行,然后解析该行并将任何单词插入到每个数组的索引中。唯一的问题是,我不知道每行有多少个单词,每行可以有1-6个单词 这就是一个简单文件的外观: 苹果橙 计算机终端键盘鼠标 如果扫描第1行,我需要一个字符数组来保存单词apple和oranges。 例如: 到目前为止,我有类似的东西,但我如何才能使它每行少于6个单词 fscanf(file, "%19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ]", strin

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

这就是一个简单文件的外观:

苹果橙

计算机终端键盘鼠标

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

到目前为止,我有类似的东西,但我如何才能使它每行少于6个单词

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

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

您可以这样做:

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
         */

      }

为什么不通读整行呢?使用空格分隔符进行分割?
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
         */

      }