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?