0

I have a file, in which each line contains several words that are separated by variable amount of whitespace characters (spaces and tabs). For example:

do that param1   param2  param3
do   this   param1

(The number of words in a line is unknown in advance and is unbounded)

I'm looking for a way to parse such a line in plain C, so that I'll have a pointer to string containing the first word, a pointer to a string containing the second word, and a pointer to a string containing everything else (that is - all of the line, except the first two words). The idea is that the "rest of the line" string will be further parsed by a callback function, determined by the first two words).

Getting the first two words is easy enough (a simple sscanf), but I have no idea how to get the "rest of the line" pointer (As sscanf stops at whitespace, and I don't know the amount of whitespace before the first word, and between the first and the second word).

Any idea will be greatly appreciated.

IgKh
  • 925
  • 8
  • 10
  • 3
    This have been covered so many times on stackoverflow. Look for the strtok function and also use the search box on this page. – karlphillip Apr 16 '11 at 17:27
  • 1
    http://stackoverflow.com/questions/2160199/reading-characters-from-a-stream-up-to-whitespace-using-isspace-in-c/2160209#2160209 – karlphillip Apr 16 '11 at 17:29
  • I thought about using `strtok` and than `strcat` but I hoped there might be a more elegant solution. – IgKh Apr 16 '11 at 17:29
  • @karlphillip: neither `strtok` nor answer you've suggested is a particularly good answer to this question. You could do things that way, but either would add considerable work to a fairly simple problem. – Jerry Coffin Apr 16 '11 at 17:31
  • Start by reading the file with `getline` or some other *safe* line reader, or just dive into full blown parsing ala [compiler methods](http://stackoverflow.com/q/1669/2509). – dmckee --- ex-moderator kitten Apr 16 '11 at 18:58

1 Answers1

3

You can use sscanf for the rest of the line as well. You just use a "scanset" conversion instead of a string conversion:

char word1[256], word2[256], remainder[1024];

sscanf(input_line, "%255s %255s %1023[^\n]", word1, word2, remainder);
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111