sscanf() function in C++

In this guide, you will learn what is sscanf() function is in C++ programming and how to use it with an example.

1. sscanf() Function Overview

The sscanf() function, a part of the <cstdio> library in C++, is used to extract formatted input from a given C-string. This function works similarly to the scanf() function, but instead of reading from standard input, it reads and parses data from a given character array.

Signature:

int sscanf(const char* str, const char* format, ...);

Parameters:

- str: Pointer to the C-string that holds the content to be parsed.

- format: A string that contains text and format specifiers, which define the expected data types for the subsequent arguments.

- ...: Variable number of arguments where the extracted values are stored.

2. Source Code Example

#include <iostream>
#include <cstdio>

int main() {
    int age;
    char name[50];
    const char* data = "JohnDoe 25";

    // Parse data and store the results in name and age
    sscanf(data, "%s %d", name, &age);

    // Print the results
    std::cout << "Name: " << name << "\nAge: " << age << std::endl;

    return 0;
}

Output:

Name: JohnDoe
Age: 25

3. Explanation

1. We define an integer age and a character array name to store the parsed values. The string data contains the content we want to parse.

2. The sscanf() function extracts values from the data string based on the format specifiers provided and stores the extracted values in the name array and age variable.

3. Finally, the extracted values name and age are printed using std::cout.

Note: sscanf() can be a potential source of errors, especially if the source string does not match the expected format. It's advisable to check the function's return value to determine the number of successfully parsed items.


Comments