In C, the sscanf function is handy for parsing strings and extracting specific data. This article provides a detailed explanation of sscanf, covering its basic usage, advanced techniques, and cautions. When learning C, you’ll often encounter situations like “I want to process user‑entered data” or “I need to extract numbers from a string.” Understanding the difference from scanf and using sscanf appropriately lets you write programs that are safer and more flexible. In this article, we’ll cover the following points.
sscanf function basics
How to use sscanf (with sample code)
Advanced techniques using sscanf
Common mistakes and how to address them
Precautions for using sscanf safely
So, let’s start by looking at the basic role of sscanf.
2. What is the C language sscanf function?
2.1 Overview of sscanf
sscanf is a function included in the C standard library that parses a string and converts it to specified data types. It is similar to scanf, but sscanf differs in that it obtains data from a string rather than standard input.
2.2 Basic syntax of sscanf
The basic format of sscanf is as follows.
int sscanf(const char *str, const char *format, ...);
str: the string to be parsed
format: format specifier (defines the data type)
...: variables (pointers) to store the converted values
It returns, as its return value, the number of input items successfully converted. On failure, it returns 0 or EOF (-1).
2.3 Differences from scanf
The differences between sscanf and scanf are summarized in the table below.
Item
sscanf
scanf
Input source
String
Standard input (keyboard)
Purpose
Parse existing strings
Receive user input
Flexibility
High (format can be specified)
Low (input constraints exist)
Security
Lower safety (risk of buffer overflow)
Difficult to control input
Error handling
Can be handled appropriately using the return value
Requires real‑time handling because it reads from standard input
Thus, sscanf is suitable for parsing existing strings and is used differently from standard input.
3. Basic Usage of sscanf (with Sample Code)
By using sscanf, you can retrieve values such as integers, floating-point numbers, and strings from a string. Here we explain the basic usage and present it with sample code.
3.1 Basic Syntax of sscanf
The basic syntax when using sscanf is as follows.
int sscanf(const char *str, const char *format, ...);
str: the string to be parsed
format: format specifiers (e.g., %d, %f, %s, etc.)
...: pointers to variables where data will be stored
It returns the number of input items successfully converted as the return value. If an error occurs, it returns 0 or EOF (-1).
3.2 Getting an Integer from a String
Let’s see how to obtain an integer from a string using sscanf.
In this way, by combining %s and %d, you can retrieve a string and a number simultaneously.
3.5 Using the Return Value of sscanf
By checking the return value of sscanf, you can determine whether the parsing succeeded.
#include <stdio.h>
int main() {
char str[] = "42";
int num;
int result = sscanf(str, "%d", &num);
if (result == 1) {
printf("Success: %d\n", num);
} else {
printf("Failure\n");
}
return 0;
}
Output
Success: 42
A return value of 1 indicates that one value was successfully obtained. In case of failure, it becomes 0 or EOF, enabling appropriate error handling.
3.6 Summary
Using sscanf, you can obtain integers, floating-point numbers, strings, etc., from a string.
It is also possible to retrieve multiple data items simultaneously.
By checking the return value of sscanf, you can perform error handling.
4. Advanced sscanf Techniques
sscanf can be used not only for basic numeric and string extraction but also for more advanced data parsing. Here we will explain in detail the following advanced uses: leveraging format specifiers, extracting specific data, parsing comma‑separated data, handling different data types, and error handling.
4.1 Mastering Format Specifiers
When you make good use of sscanf‘s format specifiers, you can achieve more flexible data parsing. In particular, the following combinations of specifiers allow you to handle different data types.
Specifier
Description
%d
Get integer
%f
Get floating‑point number
%s
Get string (whitespace‑delimited)
%c
Get a single character
%[A-Za-z]
Get a string of characters within a specific range
Example: Retrieving a String Containing Spaces
The normal %s reads a string up to whitespace, but by using %[^ ] you can capture all characters up to a newline.
It is important to use the return value of sscanf to perform error checking.
Example: Performing Input Validation
#include <stdio.h>
int main() {
char str[] = "42";
int num;
int result = sscanf(str, "%d", &num);
if (result == 1) {
printf("Success: %d\\n", num);
} else {
printf("Failure\\n");
}
return 0;
}
Output
Success: 42
In this way, by checking the return value of sscanf you can properly handle input errors.
4.6 Summary
sscanf‘s format specifiers enable flexible data parsing.
You can extract specific data (such as dates/times or comma‑separated values).
By using the return value of sscanf, you can perform error checks and ensure safe processing.
5. Precautions and Security Risks When Using sscanf
sscanf is a convenient function, but if used incorrectly it can cause buffer overflows and unexpected behavior. Especially when processing data received from external sources, proper error handling and validation are required. Here we explain the points to watch out for when using sscanf and how to avoid security risks.
5.1 Risk of Buffer Overflows
When using sscanf, failing to consider appropriate buffer sizes can lead to buffer overflows.
The size of name is 10 bytes, but "VeryLongUserName" is 16 bytes.
A buffer overflow can occur, potentially corrupting memory.
Safe Code Example
#include <stdio.h>
int main() {
char name[10];
char str[] = "VeryLongUserName";
sscanf(str, "%9s", name); // Specify 9 to read up to 9 characters plus the terminating '\0'
printf("Name: %sn", name);
return 0;
}
Using %9s limits the read to at most 9 characters, preventing memory corruption.
5.2 Error Checking for Unexpected Input
If you don’t check the return value of sscanf, the program may behave incorrectly when given malformed data.
Problematic Code
#include <stdio.h>
int main() {
char str[] = "abc";
int num;
sscanf(str, "%d", &num); // Fails, but no error check
printf("Retrieved number: %dn", num);
return 0;
}
In this case, the value of num is indeterminate (garbage), which can cause unintended behavior.
Safe Code
#include <stdio.h>
int main() {
char str[] = "abc";
int num;
if (sscanf(str, "%d", &num) == 1) {
printf("Retrieved number: %dn", num);
} else {
printf("Error: Could not retrieve the number.\n");
}
return 0;
}
Output
Error: Could not retrieve the number.
This allows the program to continue safely even when the input is incorrect.
5.3 Validating Input Data
When unexpected data arrives, the program’s behavior can become unstable. Therefore, it is important to validate the data before using sscanf.
Example: User Input Validation
#include <stdio.h>
#include <ctype.h>
int is_number(const char *str) {
while (*str) {
if (!isdigit(*str)) return 0; // Error if a non-digit character is found
str++;
}
return 1;
}
int main() {
char input[] = "42a"; // Invalid as a number
int num;
if (is_number(input)) {
sscanf(input, "%d", &num);
printf("Retrieved number: %dn", num);
} else {
printf("Error: Invalid number entered.\n");
}
return 0;
}
Output
Error: Invalid number entered.
By checking in advance that the data is numeric, safe processing becomes possible.
5.4 Safe String Handling Combined with fgets
You can also use fgets instead of sscanf to safely handle input.
Getting Safe Strings
#include <stdio.h>
int main() {
char buffer[100];
printf("Please enter a string: ");
fgets(buffer, sizeof(buffer), stdin);
printf("Retrieved string: %s", buffer);
return 0;
}
fgets prevents buffer overflows while obtaining user input, so using it together with sscanf improves safety.
5.5 Summary
Set a maximum length in format specifiers to prevent buffer overflows.
Check the return value to confirm that data retrieval succeeded.
Validate input data in advance to prevent processing of malformed data.
Leverage fgets and similar functions for safe input handling.
6. Common Mistakes and Their Solutions
sscanf is a handy function, but using it incorrectly can cause unintended behavior. This section provides a detailed explanation of mistakes beginners often make and how to fix them.
6.1 Segmentation Fault Caused by Misusing Pointers
Incorrect Code
#include <stdio.h>
int main() {
char *str = "123 456"; // string literals are immutable
int a, b;
sscanf(str, "%d %d", &a, &b);
printf("a = %d, b = %dn", a, b);
return 0;
}
This code uses sscanf to read integers, but str points to a string literal ("123 456"), which resides in read‑only memory. Solution: Use the char str[] form.
Corrected Code
#include <stdio.h>
int main() {
char str[] = "123 456"; // defined as an array (modifiable)
int a, b;
sscanf(str, "%d %d", &a, &b);
printf("a = %d, b = %dn", a, b);
return 0;
}
6.2 Incorrect Format Specifier
Incorrect Code
#include <stdio.h>
int main() {
char str[] = "123.45";
int num;
sscanf(str, "%d", &num); // attempting to parse as an integer
printf("Read number: %dn", num);
return 0;
}
In this code, "123.45" is being parsed as an integer with %d. Because of the decimal point, the value cannot be read correctly. Solution: Use %f.
#include <stdio.h>
int main() {
char str[] = "abc";
int num;
sscanf(str, "%d", &num); // string "abc" cannot be converted to a number
printf("Read number: %dn", num);
return 0;
}
"abc" cannot be converted to an integer, so num ends up with a garbage value, causing unintended behavior. Solution: Check the return value of sscanf.
Corrected Code
#include <stdio.h>
int main() {
char str[] = "abc";
int num;
if (sscanf(str, "%d", &num) == 1) {
printf("Read number: %dn", num);
} else {
printf("Error: Could not read a number.n");
}
return 0;
}
%s treats whitespace as a delimiter by default, so the "World" part of Hello World ends up in a separate variable. Solution: Use %[^ ] to read the string up to a newline.
If the value exceeds the maximum for the int type (typically 2147483647), a overflow occurs, leading to unexpected behavior. Solution: Use long long.
Corrected Code
#include <stdio.h>
int main() {
char str[] = "999999999999";
long long num;
sscanf(str, "%lld", &num);
printf("Read number: %lldn", num);
return 0;
}
Output
Read number: 999999999999
6.6 Summary
Avoid misusing pointers and allocate appropriate memory.
Prevent format specifier mistakes by using specifiers that match the data type.
Always perform error checks to prevent unexpected behavior.
When reading strings that contain spaces, use %[^ ].
If a value exceeds the range of int, use long long.
Check to ensure you do not pass a NULL pointer.
7. FAQ (Frequently Asked Questions)
This section provides a detailed explanation of the common questions developers often have when using sscanf. It answers them with concrete examples, covering everything from basic usage to advanced applications.
7.1 What are the differences between sscanf and scanf?
scanf and sscanf are both functions that retrieve data based on format specifiers, but the source of input differs.
Item
sscanf
scanf
Input source
String (char[])
Standard input (stdin)
Purpose
Parse an existing string
Obtain user input
Flexibility
High (easy data conversion)
Low (real-time input)
Error handling
Easy
Difficult
Example: Using scanf
#include <stdio.h>
int main() {
int num;
printf("Please enter a number: ");
scanf("%d", &num);
printf("Entered number: %dn", num);
return 0;
}
Difference between scanf and sscanf → sscanf is suited for string parsing
Retrieving strings that contain spaces → use %[^ ]
Error checking → verify the return value of sscanf
Simultaneous retrieval of numbers and strings → specify the format correctly
Alternative methods → determine when to use strtok
Safe usage → Specify buffer sizes, perform error checking, and combine with fgets
8. Summary
In this article, we explained the C language sscanf function in detail, covering basic usage, advanced techniques, cautions, common mistakes and their solutions, and FAQs. Finally, we summarize the key points and introduce best practices for using sscanf safely and effectively.
8.1 Article Summary
✅ sscanf Basics
sscanf is a function that parses data from a string.
Unlike scanf, it processes a string instead of standard input.
Basic syntax:
int sscanf(const char *str, const char *format, ...);
You can use format specifiers to retrieve integers, floating-point numbers, strings, etc.
→ sscanf is for format specification, strtok is for token splitting!
8.4 To make use of this article
📌 Write code and try it out 📌 Learn variations of format specifiers 📌 Cultivate awareness of writing safe code
8.5 Summary
🔹 sscanf is a convenient function for parsing data from strings 🔹 Basic usage to advanced techniques can be widely applied
🔹 Understanding cautions and performing proper error handling is important
🔹 Enhance safety by specifying buffer sizes and combining with fgetsLet’s use sscanf correctly and practice safe C programming!