Sai A Sai A
Updated date Oct 16, 2023
In this blog, we will explore the process of converting strings to integers in C++. Learn about multiple methods, from the widely-used std::stoi function to the versatile std::stringstream and the efficient std::from_chars introduced in C++17.

Introduction:

One of the fundamental tasks in programming is converting data from one type to another. In C++, converting a string to an integer is a common operation, especially when dealing with user input or reading data from external sources. In this blog, we will explore multiple methods for converting a string to an integer in C++ and discuss their strengths and weaknesses.

Method 1: Using stoi Function

The stoi function in C++ stands for "string to integer." It is part of the <string> header and is a straightforward way to convert a string to an integer. Let's look at a simple program that demonstrates this method:

#include <iostream>
#include <string>

int main() {
    // Method 1: Using stoi function
    std::string str = "123";
    int convertedInt = std::stoi(str);

    // Output
    std::cout << "Method 1 Output: " << convertedInt << std::endl;

    return 0;
}

Output:

Method 1 Output: 123

Method 2: Using stringstream

Another method involves using the std::stringstream class from the <sstream> header. This approach allows for more flexibility and additional error handling. Here's an example program:

#include <iostream>
#include <sstream>

int main() {
    // Method 2: Using stringstream
    std::string str = "456";
    std::stringstream ss(str);
    int convertedInt;
    ss >> convertedInt;

    // Output
    std::cout << "Method 2 Output: " << convertedInt << std::endl;

    return 0;
}

Output:

Method 2 Output: 456

Method 3: Using std::from_chars (C++17 and later)

Starting from C++17, the <charconv> header introduces the std::from_chars function, providing an efficient and flexible way to convert strings to numeric types. Here's an example program:

#include <iostream>
#include <charconv>

int main() {
    // Method 3: Using std::from_chars (C++17 and later)
    std::string str = "789";
    int convertedInt;
    std::from_chars(str.data(), str.data() + str.size(), convertedInt);

    // Output
    std::cout << "Method 3 Output: " << convertedInt << std::endl;

    return 0;
}

Output:

Method 3 Output: 789

Conclusion:

In this blog, we have discussed several methods for converting a string to an integer in C++. The std::stoi function is simple and widely used, while the std::stringstream approach offers more control and error handling. The introduction of std::from_chars in C++17 provides a performant solution with the added benefit of error reporting.

Comments (0)

There are no comments. Be the first to comment!!!