1

My input is from a file with multiple lines of text. After obtaining a line with fgets() how do I make an array containing the words from that line, which I can then iterate through? ie. from "pink floyd" to {"pink", "floyd"}.

int main() {
    char line[500];
    while(fgets(line, sizeof(line), stdin) != NULL) {
        ...
    }
    return 0;
}
Pybert
  • 13
  • 4
  • 1
    1. Make a new array; 2. Cycle through the words in the line and copy each one into your new array. – Crowman Sep 21 '14 at 23:56

1 Answers1

1

You can extract words from a line of text using the strtok() function. See How does the strtok function in C work? and http://www.cplusplus.com/reference/cstring/strtok/.

The strtok() function will modify the contents of line[], but I suppose that's OK for this usage because you just wrote a line of input there and you will soon write another line of input over it.

You will have to allocate a separate array to hold the pointers to the individual words. If you intend to keep using this array after reading the next line of input, you will need to make new copies of the strings returned by strtok(), because what it returns is pointers into char line[500] and the next line of input will overwrite them.

Community
  • 1
  • 1
David K
  • 3,147
  • 2
  • 13
  • 19