A quick summary of my use of sscanf. It may not answer all of your questions, but it's a start.
My code:
1 2 3
|
int n;
char ch;
int count = 0;
|
sscanf(p, " %d%c%n", &n, &ch, &count)
p
is a pointer to the input character array (string).
Format string: " %d%c%n"
• space - ignore leading whitespace (not really needed here).
• %d - read an integer
• %c - read a character, in this case the comma separator (or the ending '!')
• %n - don't read anything, but return the number of characters read from the string.
These items are stored in the variables passed by a pointer to each. In the same order as the format string,
&n, &ch, &count
That will just read a single integer, and a single comma. The useful part is to increment the pointer by the value of count. That makes it ready to read the next part of the string.
By the way, you should also refer to the reference page and consider that alongside my own comments:
sscanf - just a special case of scanf, which works with strings, hence the extra 's' in its name.
http://www.cplusplus.com/reference/cstdio/sscanf/
scanf - get formatted input:
http://www.cplusplus.com/reference/cstdio/scanf/
its actually doing something extra that I was planning to do , meaning I was planning to extract the string from first '\n' char to the next '\n' char and process this substring only but your code actually is doing that . |
Maybe my code isn't quite doing that. My input string ends with a trailing exclamation mark '!', there is nothing else after that.
The code could be modified to stop when it hits the '!', if that would be reliable. If not, you might want to start by copying a just the substring which is enclosed between the first and second newlines, and use that substring as the input. I can think of other ideas, such as modifying the original string (that's what strtok does).
Edit: one tricky part of the code is the return value from the function sscanf(). Usually we hope it will read two values, an integer and a character. The return value should be 2 in that case. When the end of the string is reached it will return EOF which is a special value reserved by the compiler, it may be -1.
http://www.cplusplus.com/reference/cstdio/EOF/