I’m trying to split a long string with white-spaces, using sscanf().
For example: I need to split this
We're a happy family
into
We're
a
happy
family
I tried the following approach
char X[10000];
fgets(X, sizeof(X) - 1, stdin); // Reads the long string
if(X[strlen(X) - 1] == '\n') X[strlen(X) - 1] = '\0'; // Remove trailing newline
char token[1000];
while(sscanf(X, "%s", token) != EOF) {
printf("%s | %s\n", token, X);
}
The previous code goes into an infinite loop outputting We're | We're a happy family
I tried to replace sscanf() with C++ istringstream, it worked fine.
What makes X keep it’s value? Shouldn’t it be removed from buffer like normal stream?
sscanf()does store information about the buffer it previously read from and will always start from the address (buffer) passed to it. A possible solution would be to the use%nformat specifier to record the position the lastsscanf()stopped at and passX + posas the first argument tosscanf(). For example:See demo at http://ideone.com/XBDTWm .
Or just use
istringstreamandstd::string: