Convert string to int in C++

Filed Under: C++
String To Int Cpp

In this article, we will look at how we can convert a string to int in C++. Often, we may need to convert numeral strings into integers. We may need certain ways to quickly do the conversion

Let’s take a look at various ways to convert a string to int.


Method 1 – Using std::stoi

To convert a std::string object to an integer, this is the recommended option in C++. This takes in a string as input and returns an integer.

Here is a simple example:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string inp = "102";
    cout << "Input String: " << inp << endl;

    // Use std::stoi() to convert string to integer
    int res = stoi(inp);

    cout << "Integer: " << res << endl;
    return 0;
}

Output

Input String: 102
Integer: 102

This will work for negative value strings also.

However, this will throw a std::invalid_argument exception if the string is not of the proper format.

Because of this, we must use Exception Handling in our code, if the string is not validated.

#include <iostream>
#include <string>

using namespace std;

int main() {
    string inp = "Hello";

    cout << "Input String: " << inp << endl;

    // Use std::stoi() to convert string to integer
    try {
        // Wrap up code in try-catch block if string is not validated
        int res = stoi(inp);
        cout << "Integer: " << res << endl;
    }
    catch(std::invalid_argument e) {
        cout << "Caught Invalid Argument Exception\n";
    }
    return 0;
}

Output

Input String: Hello
Caught Invalid Argument Exception

Hopefully that gives you a good idea of how you can convert a String into a Integer in C++.

We’ll also present one more way, using the C-style atoi() function.


Method 2 – Using atoi()

We can convert a C string (char*) into an integer, using atoi(char* str).

We can apply this logic to our std::string object, by first converting into a C string.

#include <iostream>
#include <string>

using namespace std;

int main() {
    string inp = "120";

    cout << "Input String: " << inp << endl;

    // Convert std::string to C-string
    const char* c_inp = inp.c_str();

    // Use atoi() to convert C-string to integer
    int res = atoi(c_inp);

    cout << "Integer: " << res << endl;
    return 0;
}

Output

Input String: 120
Integer: 120

As you can see, this gives us the same result as before!


Conclusion

In this article, we learned how we could convert a string to int in C++.

For similar content, do go through our tutorial section on C++ programming.

References


Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages