1

A brief question really, looking for, wondering about, and asking for any tips for what the best way is to handle this type of input:

 word word
 word word word word
 word word word
 word word

whereby the number of words on each line is totally random, and each separate word can be added to some data structure, like a linked list or tree for example.

Fgets each line and parse? Getchar()? Any clues?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
PnP
  • 3,133
  • 17
  • 62
  • 95

1 Answers1

2

Reading one line at a time with fgets seems like the best option here. Then just use strtok or something similar to split by empty space and iterate over the result.

Tudor
  • 61,523
  • 12
  • 102
  • 142
  • 2
    Be aware that `strtok()` destroys its input as it processes it. It is also not thread-safe, and you have to be sure that no other function that you call from your parser uses `strtok()`, and that no function that calls your parser uses `strtok()`. The condition on functions called is usually not too onerous; in library code, though, the second condition (no calling function also using `strtok()`) is not enforceable. – Jonathan Leffler Dec 11 '11 at 21:14
  • Is there another way you would recommend, I'm not really comfortable with strtok – PnP Dec 11 '11 at 21:21
  • @user1048116: strtok_r is the thread-safe version. Anyway, in your situation, I don't think that you need to worry about what Jonathan Leffler pointed out. – Tudor Dec 11 '11 at 21:24
  • Agreed; for the immediate purpose at hand, `strtok()` will probably be adequate. But it is as well to know about the weaknesses in tools you are using so as not to get bitten later. – Jonathan Leffler Dec 11 '11 at 21:51