I have this program that is supposed to read a line e.g post "nice job" john
and i want to get every token in that line but for some reason i only get some of them.
Expected output:
post
nice job
john
My output:
post
nice
im sure im putting the correct format on sscanf so whats the problem i dont get why it doenst consider "nice job" as one word.
Program:
#include <stdio.h>
int main()
{
char token1[128];
char token2[128];
char token3[128];
char str[] = "post \"nice job\" john";
sscanf(str,"%s \"%s\" %s",token1,token2,token3);
puts(token1);
puts(token2);
puts(token3);
return(0);
}
CodePudding user response:
The second %s
reads "nice"
because %s
stops at the first whitespace. The format string then demands a match for a "
quote, which isn't next (a space is next). The scanf
functions don't skip input until a match is found, they stall. Always check the return value which should have been 3
.
This code
#include <stdio.h>
int main()
{
char token1[128] = "";
char token2[128] = "";
char token3[128] = "";
char str[] = "post \"nice job\" john";
int res = sscanf(str, "%s \"%[^\"]\"%s", token1, token2, token3);
printf("%d\n", res);
puts(token1);
puts(token2);
puts(token3);
return(0);
}
outputs
3
post
nice job
john