C sscanf: Full Guide, Tips & Pitfalls (Beginner Code)

目次

1. Introduction

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.
Itemsscanfscanf
Input sourceStringStandard input (keyboard)
PurposeParse existing stringsReceive user input
FlexibilityHigh (format can be specified)Low (input constraints exist)
SecurityLower safety (risk of buffer overflow)Difficult to control input
Error handlingCan be handled appropriately using the return valueRequires 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.
#include <stdio.h>

int main() {
    char str[] = "123";
    int num;

    sscanf(str, "%d", &num);
    printf("Obtained value: %d\n", num);

    return 0;
}
Output
Obtained value: 123
In this way, by specifying "%d", you can retrieve the integer 123 from the string "123".

3.3 Getting Multiple Values from a String

Using sscanf, you can also retrieve multiple values from a single string.
#include <stdio.h>

int main() {
    char str[] = "100 200";
    int a, b;

    sscanf(str, "%d %d", &a, &b);
    printf("a = %d, b = %d\n", a, b);

    return 0;
}
Output
a = 100, b = 200
It is useful when parsing space-separated data.

3.4 Getting a String and a Number Simultaneously

Next, we introduce how to parse both a string and a number using sscanf.
#include <stdio.h>

int main() {
    char str[] = "name: John age: 30";
    char name[50];
    int age;

    sscanf(str, "name: %s age: %d", name, &age);
    printf("Name: %s, Age: %d\n", name, age);

    return 0;
}
Output
Name: John, Age: 30
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.
SpecifierDescription
%dGet integer
%fGet floating‑point number
%sGet string (whitespace‑delimited)
%cGet 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.
#include <stdio.h>

int main() {
    char str[] = "Hello World!";
    char result[50];

    sscanf(str, "%[^\\n]", result);
    printf("Retrieved string: %s\\n", result);

    return 0;
}
Output
Retrieved string: Hello World!
In this way, using %[^ ] allows you to correctly retrieve strings that contain spaces.

4.2 Extracting Specific Data

sscanf is also suitable for extracting specific data from a string.

Example: Parsing a Date

For example, from a date string like “2025-02-01” you can extract the year, month, and day separately.
#include <stdio.h>

int main() {
    char date[] = "2025-02-01";
    int year, month, day;

    sscanf(date, "%d-%d-%d", &year, &month, &day);
    printf("Year: %d, Month: %d, Day: %d\\n", year, month, day);

    return 0;
}
Output
Year: 2025, Month: 2, Day: 1

4.3 Parsing Comma‑Separated Data

When processing CSV (Comma‑Separated Values) data, using sscanf is handy.

Example: Parsing CSV Data

#include <stdio.h>

int main() {
    char input[] = "Apple,120,2.5";
    char product[20];
    int quantity;
    float price;

    sscanf(input, "%[^,],%d,%f", product, &quantity, &price);
    printf("Product: %s, Quantity: %d, Price: %.2f\\n", product, quantity, price);

    return 0;
}
Output
Product: Apple, Quantity: 120, Price: 2.50

4.4 Parsing Mixed Data Types

We introduce how to process data that mixes numbers and strings using sscanf.

Example: Parsing ID, Name, and Score

#include <stdio.h>

int main() {
    char input[] = "ID123 Name:Taro Score:95";
    char id[10], name[20];
    int score;

    sscanf(input, "ID%s Name:%s Score:%d", id, name, &score);
    printf("ID: %s, Name: %s, Score: %d\\n", id, name, score);

    return 0;
}
Output
ID: 123, Name: Taro, Score: 95

4.5 Applying Error Handling

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.

Dangerous Code Example

#include <stdio.h>

int main() {
    char name[10];
    char str[] = "VeryLongUserName";

    sscanf(str, "%s", name);
    printf("Name: %sn", name);

    return 0;
}
Problem
  • 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.

Corrected Code

#include <stdio.h>

int main() {
    char str[] = "123.45";
    float num;

    sscanf(str, "%f", &num);
    printf("Read number: %.2fn", num);

    return 0;
}
Output
Read number: 123.45

6.3 Not Performing Error Checks

Incorrect Code

#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;
}
Output
Error: Could not read a number.

6.4 Failing to Read Strings Containing Spaces

Incorrect Code

#include <stdio.h>

int main() {
    char str[] = "Hello World";
    char word1[10], word2[10];

    sscanf(str, "%s %s", word1, word2);
    printf("Word1: %s, Word2: %sn", word1, word2);

    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.

Corrected Code

#include <stdio.h>

int main() {
    char str[] = "Hello World";
    char sentence[50];

    sscanf(str, "%[^
]", sentence);
    printf("Read string: %sn", sentence);

    return 0;
}
Output
Read string: Hello World

6.5 Exceeding the Numeric Range

Incorrect Code

#include <stdio.h>

int main() {
    char str[] = "999999999999";
    int num;

    sscanf(str, "%d", &num);
    printf("Read number: %dn", num);

    return 0;
}
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.
Itemsscanfscanf
Input sourceString (char[])Standard input (stdin)
PurposeParse an existing stringObtain user input
FlexibilityHigh (easy data conversion)Low (real-time input)
Error handlingEasyDifficult

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;
}
Retrieves a value from standard input (keyboard).

Example: Using sscanf

#include <stdio.h>

int main() {
    char str[] = "123";
    int num;
    sscanf(str, "%d", &num);
    printf("Parsed number: %dn", num);
    return 0;
}
Converts the existing string "123" to a number.

7.2 How to retrieve a string containing spaces with?

The default %s treats spaces as delimiters. To retrieve a string that includes spaces, use %[^ ].

Example: Retrieving a string with spaces

#include <stdio.h>

int main() {
    char str[] = "Hello World!";
    char result[50];

    sscanf(str, "%[^\n]",);
    printf("Retrieved string: %sn", result);
    return 0;
}
Output
Retrieved string: Hello World!

7.3 What does the return value of sscanf mean?

The return value of sscanf indicates the number of items successfully read. If it fails to read data, it returns 0 or EOF (‑1).

Example: Checking the return value

#include <stdio.h>

int main() {
    char str[] = "42";
    int num;
    int result = sscanf(str, "%d", &num);

    if (result == 1) {
        printf("Success: %dn", num);
    } else {
        printf("Failure\n");
    }

    return 0;
}
Output
Success: 42

7.4 How to retrieve numbers and strings simultaneously with sscanf?

Using sscanf, you can parse numbers and strings at the same time.

Example: Parsing ID, name, and score

#include <stdio.h>

int main() {
    char input[] = "ID123 Name:Taro Score:95";
    char id[10], name[20];
    int score;

    sscanf(input, "ID%s Name:%s Score:%d", id, name, &score);
    printf("ID: %s, Name: %s, Score: %dn", id, name, score);
    return 0;
}
Output
ID: 123, Name: Taro, Score: 95

7.5 How should error handling for sscanf be done?

If you don’t perform error checking, unintended data may be stored. Use the return value of sscanf to check.

Example: Input validation

#include <stdio.h>

int main() {
    char str[] = "abc";  // invalid string for numeric conversion
    int num;

    if (sscanf(str, "%d", &num) == 1) {
        printf("Retrieved number: %dn", num);
    } else {
        printf("Error: Could not retrieve a number.\n");
    }

    return 0;
}
Output
Error: Could not retrieve a number.

7.6 Should you use strtok instead of sscanf?

In some cases, strtok may be more appropriate.
tr>
Use casesscanfstrtok
String parsingUses format specifiersSpecifies delimiters
Retrieval methodRetrieves values according to the formatSplits the string into tokens
FlexibilityHigh (can retrieve integers, strings, floating‑point numbers, etc.)Suitable for processing consecutive tokens

Example: Splitting a string using strtok

#include <stdio.h>
#include <string.h>

int main() {
    char input[] = "apple,banana,orange";
    char *token = strtok(input, ",");

    while (token != NULL) {
        printf("Fruit: %sn", token);
        token = strtok(NULL, ",");
    }
    return 0;
}
Output
Fruit: apple
Fruit: banana
Fruit: orange

7.7 Summary

  • Difference between scanf and sscanfsscanf 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 usageSpecify 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.

✅ How to use sscanf

  • Retrieving numbers
  sscanf("123", "%d", &num);
  • Retrieving multiple data items
  sscanf("100 200", "%d %d", &a, &b);
  • Retrieving numbers and strings simultaneously
  sscanf("ID123 Name:Taro Score:95", "ID%s Name:%s Score:%d", id, name, &score);
  • Retrieving strings that contain spaces
  sscanf("Hello World!", "%[^\n]", buffer);

8.2 Cautions when using sscanf

Incorrect usageIssueSolution
%s without length specificationRisk of buffer overflowSpecify length, e.g., %9s
No error checkingPossibility of processing unexpected dataAlways check the return value of sscanf
Passing a NULL pointerSegmentation faultEnsure the pointer is not NULL
Retrieving 999999999999 with %dInteger overflowUse long long type and specify %lld

8.3 Best Practices for sscanf

✅ 1. Specify buffer size

char name[10];
sscanf(str, "%9s", name);  // Retrieve up to a maximum of 9 characters (plus '\\0')
Prevent buffer overflow!

✅ 2. Perform error checking

if (sscanf(str, "%d", &num) != 1) {
    printf("Error: Failed to retrieve number.\n");
}
Check whether data retrieval succeeded!

✅ 3. Combine with fgets

char buffer[100];
fgets(buffer, sizeof(buffer), stdin);
Ensure safety when handling user input!

✅ 4. Use strtok and sscanf appropriately when parsing strings

char *token = strtok(str, ",");
while (token != NULL) {
    printf("%s\n", token);
    token = strtok(NULL, ",");
}
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 fgets Let’s use sscanf correctly and practice safe C programming!

9. References

年収訴求