Convert a string to int in C++

Google Translate Icon

This post will discuss how to convert a string to int in C++.

1. Using std::stoi function

The standard approach is to use the std::stoi function for converting a string to an integer. The stoi function was introduced in C++11 and is defined in the header <string>. It throws std::invalid_argument or std::out_of_range exception on a bad input or integer overflow, respectively. It is worth noting that it will convert the strings like 10xyz to integer 10.

Download  Run Code

2. Using string streams

std::stringstream can be used to convert std::string to other data types and vice versa. This suffers from the same problem as std::stoi did, i.e., it will convert the strings like 10xyz to integer 10. It returns INT_MAX or INT_MIN if the converted value is out of the range of integer data type. If the value of the string can’t be represented as an int, 0 is returned.

Download  Run Code

3. Using boost::lexical_cast

Another good alternative is to use the boost::lexical_cast. It throws the boost::bad_lexical_cast exception when no valid integer could be constructed, or overflow happens.

Download Code

4. Using std::atoi function

We can also use the std::atoi function to convert a string to an int. It takes a C-string as a parameter, so we need to convert our string to a C-string. We can do that using std::string::c_str.

Please note that its behavior is undefined if the converted value is out of the range of integer data type. If the value of the string can’t be represented as an int, 0 is returned.

Download  Run Code

5. Using sscanf() function

We can pass a C-string to the sscanf() function as a parameter and convert it into the corresponding data type specified in the format specifier. It would return the total number of arguments on success and EOF on failure.

Download  Run Code

6. Using range-based for-loop

Finally, the naive solution is to implement our own routine. The idea is to iterate through chars of the string using Range-based for-loop (C++11) and process each digit individually. The behavior is undefined if the converted value is out of range of integer data type.

Download  Run Code

That’s all about converting a string to int in C++.

Rate this post

Average rating 4.66/5. Vote count: 58

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?




Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)



Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!