Convert string to int in C++

Convert String to int in C++

We can convert string to int in different ways. In this article, we will discuss 5 methods to convert String to int in C++.

Convert String to int in C++ using stoi()

This method was introduced in C++ 11. It is the easiest way to convert ‘string’ to ‘int’ in c++.

Code:

Output:

12345
1
999999

Note: ‘stoi()’ only returns the integer part of the decimal number without rounding off.

Convert String to int in C++ using atoi()

‘atoi()’ function can be used to convert character array or string literal to ‘int’ data type. It is defined in the ‘cstdlib’ header file.

Note: atoi() function will return zero if the value passed is invalid or if it encounters any other issue. ‘stoi()’ function will give the error message in that case.

Code:

Output:

12345
1
999999
0

Convert String to int in C++ using stringstream class

We can use stringstream class for converting strings of digits to int. This method is useful for earlier versions of C++.

Code:

Output:

123456789

Convert String to int in C++ using strtol() function (string to long integer)

The strtol() method is used to convert strings to long integers. It is a function of the C standard library and can be implemented in C++. It will not consider the white space characters at the beginning of the string and it will consider other parts as numbers. It will stop when it will encounter the first character which is not a number. (It is a better option than atoi()).
Macro Constant ERANGE=Result too large or small (out of range)
EINVAL=Invalid argument

Syntax:

Note: If the value passed for conversion is too small or too large, then it will store ERANGE in errno. If the value is too large, then it will return a value of LONG_MAX. If the value is too small, then it will return a value of LONG_MIN.

Code:

Output:

Converted string to number: 1234567890

Convert String to int in C++ using Spirit.x3 parser library of Boost

In c++, there is a header-only library Spirit.x3 of boost which can be used for parsing in C++. It can be used to parse integers with its numeric parsers. We will use the ‘boost::spirit::x3::int_parser’ for parsing the integer.

Code:

Output:

INTEGER VALUE: 123456789

Conclusion

In this article, we discussed five different methods for how to convert string to int in C++. Sometimes it can be difficult to handle errors with atoi() because if you take 0 as a valid input, then it will be difficult to identify if it is an error or not. For C++ 03 and earlier versions, the stringstream method can be used.

Happy Learning!!

Was this post helpful?

Leave a Reply

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