Javatpoint Logo
Javatpoint Logo

Stoi function in C++

The stoi is a C++ standard library function that converts a string to an integer. It stands for "string to integer". It takes a string as input and returns the corresponding integer value. The function can raise an exception of type std::invalid_argument if the input string does not represent a valid integer.

Examples of using stoi in C++:

Output

123
-456

In the first example, the string "123" is converted to the integer 123. In the second example, the string "-456" is converted to the integer -456. In the third example, the string "7.89" is not a valid integer, so a std::invalid_argument exception is thrown.

Other example code snippet:

Output

100
512
192
Invalid argument: abc

The first example converts the string "100" to the decimal integer 100. In the second example, the string "200" is converted to the hexadecimal integer 512 by passing 0 as the second argument and 16 as the third argument to stoi.

In the third example, the string "300" is converted to the octal integer 192 by passing nullptr as the second argument and 8 as the third argument to stoi.

In the fourth example, the string "abc" is not a valid integer, so a std::invalid_argument exception is thrown.


Next TopicToLOWER In C++





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA