In C, the sscanf function is used to read formatted input from a string. Typically, sscanf stops reading upon encountering a space, as space is considered the default delimiter for strings. However, if you want to read a string containing spaces, you need to use specific format specifiers in the format string.
For example, if you have a string containing a person's full name with spaces between the name parts, you can use %[^ ] to read the entire line until a newline character is encountered, or %[^ ] until a tab character is encountered, or more commonly, use "%[^"]" to read until another quotation mark. Here, ^ denotes the start of a negated character class, meaning it matches any character except those specified.
Example
Suppose we have the following string, which needs to extract the first and last names:
cchar info[] = "John Smith"; char firstName[100], lastName[100]; // Using sscanf to read a string containing spaces sscanf(info, "%s %[^ ]", firstName, lastName); printf("First Name: %s\n", firstName); printf("Last Name: %s\n", lastName);
In this example, %s reads the first word "John" into the firstName variable. %[^ ] reads from the first space until a newline character is encountered, storing the remaining part "Smith" into the lastName variable.
Note that %[^ ] is used here to ensure that strings containing spaces can be read. If you only use %s, it will stop reading upon encountering a space, so you would only get "John".
Important Notes
- When using
%[...], ensure that the destination array has sufficient space to store the expected string; otherwise, it may lead to buffer overflow. - Generally, for safety, it is best to use a maximum width (e.g.,
%99[^ ]) to avoid buffer overflow due to excessively long strings. - The return value of
sscanfcan be used to check the success of the input operation; it returns the number of successfully read input items.
By doing this, you can flexibly extract various formatted data containing spaces from strings.