C++ – Convert String to Int in C++

How to Convert String to int in C++ Language?

Often, there is a need to convert string to int in C++ you can convert string in two ways: using built-in functions or write your own function, so let’s solve this problem.

Manual conversion

Example of converting to base 10 (C++ function)

An example of converting to base 10 a string to int in C++ without using library function as stoi().

Output:String To Int in C++ using custom function (dec)

This function throws an exception in the case of:

  • when the string is empty;
  • when the first character is not ‘-‘ or a digit;
  • or when the string contains a not digit character.

Example of converting in specified base (C++ function)

Output:String To Int in C++ custom function

Descriptions of the program

The function char2decBase converts the char c to decimal number in base int numberBase.

The function string2int converts the string stringNumber to int number in base int numberBase (eg: decimal, binary, hexa). The base range is from 2 till 36.

  1. Check if the string is not empty
  2. Check if a number is within a range [2, 36]
  3. Check the sign
  4. The String to int in base 10 conversion loop
  5. Return the result, if the number is negative then change the sign of the number

Convert string to int in C++ using the stoi() function

Parses str interpreting its content as an integral number of the specified base, which is returned as an int value.
If idx is not a null pointer, the function also sets the value of idx to the position of the first character in str after the number.



str – the string object with the representation of a number.
idx – Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
base- Numerical base (radix) that determines the valid characters and their interpretation.

Notice that by default this argument is 10, not 0.

Return Value

On success, the function returns the converted integral number as an int value.


Output:String To Int in C++ - stoi() function


std::invalid_argument in case if no conversion could be performed
std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function ( std::strtol or std::strtoll) sets errno to ERANGE.
In case of an invalid idx causes undefined behavior.

stoi – C++ Reference
C++ – Wikipedia
Exception handling – Wikipedia, the free encyclopedia

Leave a Reply

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