Parsing a line in C
I have a file, in wh开发者_JAVA技巧ich 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.
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);
精彩评论