How to Use sscanf in C: Syntax, Example, and Tips
In C,
sscanf reads formatted data from a string into variables using a format specifier. You provide the source string, a format string describing the data layout, and pointers to variables where the extracted values will be stored.Syntax
The sscanf function reads data from a string according to a format and stores it in variables. Its syntax is:
int sscanf(const char *str, const char *format, ...);
- str: The input string to read from.
- format: A format string specifying the expected data types and layout.
- ...: Pointers to variables where the extracted values will be stored.
The function returns the number of input items successfully matched and assigned.
c
int sscanf(const char *str, const char *format, ...);
Example
This example shows how to use sscanf to extract an integer and a float from a string.
c
#include <stdio.h> int main() { const char *input = "123 45.67"; int i; float f; int count = sscanf(input, "%d %f", &i, &f); printf("Items matched: %d\n", count); printf("Integer: %d\n", i); printf("Float: %.2f\n", f); return 0; }
Output
Items matched: 2
Integer: 123
Float: 45.67
Common Pitfalls
Common mistakes when using sscanf include:
- Not passing pointers to variables (forgetting the
&). - Using incorrect format specifiers that don't match the data.
- Not checking the return value to confirm how many items were read.
- Assuming input is always well-formed, which can cause errors.
Always check the return value and ensure your format matches the input string.
c
#include <stdio.h> int main() { const char *input = "100 abc"; int i; float f; // Wrong: missing & for i // int count = sscanf(input, "%d %f", i, &f); // This causes undefined behavior // Correct: int count = sscanf(input, "%d %f", &i, &f); printf("Items matched: %d\n", count); if (count == 2) { printf("Integer: %d, Float: %.2f\n", i, f); } else { printf("Input format mismatch or incomplete data.\n"); } return 0; }
Output
Items matched: 1
Input format mismatch or incomplete data.
Quick Reference
| Format Specifier | Description |
|---|---|
| %d | Reads an integer |
| %f | Reads a float |
| %s | Reads a string until whitespace |
| %c | Reads a single character |
| %lf | Reads a double |
| %x | Reads a hexadecimal integer |
Key Takeaways
Use
sscanf to read formatted data from strings into variables by providing pointers.Always match format specifiers to the expected data types in the input string.
Check the return value of
sscanf to ensure the correct number of items were read.Remember to pass variable addresses (using
&) to store the extracted values.Avoid assuming input format is always correct; handle mismatches gracefully.