For a project I'm trying to read an int and a string from a string. The only problem is sscanf()
appears to break reading an %s
when it sees a space. Is there anyway to get around this limitation? Here's an example of what I'm trying to do:
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { int age; char* buffer; buffer = malloc(200 * sizeof(char)); sscanf("19 cool kid", "%d %s", &age, buffer); printf("%s is %d years old\n", buffer, age); return 0; }
What it prints is: cool is 19 years old
where I need cool kid is 19 years old
. Does anyone know how to fix this?
Once the character is equal to New-line ('\n'), ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);
You can't do this work with the sscanf function and a "central" string with an arbitrary number of spaces in it, since the whitespace is also your delimiter for the next field; if that %s matched strings with whitespace, it would "eat" also the 6.
Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed. scanf("%d "); scanf(" %d"); scanf("%d\n"); This is different from scanf("%d"); function.
The following line will start reading a number (%d
) followed by anything different from tabs or newlines (%[^\t\n]
).
sscanf("19 cool kid", "%d %[^\t\n]", &age, buffer);
You want the %c
conversion specifier, which just reads a sequence of characters without special handling for whitespace.
Note that you need to fill the buffer with zeroes first, because the %c
specifier doesn't write a nul-terminator. You also need to specify the number of characters to read (otherwise it defaults to only 1):
memset(buffer, 0, 200); sscanf("19 cool kid", "%d %199c", &age, buffer);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With