Reading words in line and putting them in array

2019-08-06 11:07发布

问题:

I need my program to read a line of a file, and then parse the line and insert any words into an index of each array. The only problem is that I don't know how many words there are per line, it can be 1-6 words per line.

So this is what a simple file can look like:

apple oranges

computer terminal keyboard mouse

I would need a char array to hold the words apple and oranges if I am scanning line 1. Example:

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

So far, I have something like this, but how can I make it so it works with fewer than 6 words per line?

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

回答1:

You are reading the entire file, not a line.

You can do something like this:

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

      }


标签: c scanf