1#include <iostream>
2#include <string>
3
4int main() {
5
6 std::string str = "123";
7 int num;
8
9 // using stoi() to store the value of str1 to x
10 num = std::stoi(str);
11
12 std::cout << num;
13
14 return 0;
15}
1// For C++11 and later versions
2string str1 = "45";
3string str2 = "3.14159";
4string str3 = "31337 geek";
5
6int myint1 = stoi(str1);
7int myint2 = stoi(str2);
8int myint3 = stoi(str3);
9
10// Output
11stoi("45") is 45
12stoi("3.14159") is 3
13stoi("31337 geek") is 31337
1#include <iostream>
2#include <string>
3using namespace std;
4int main() {
5
6 string s = "10";
7
8 try
9 {
10 int i = stoi(s);
11 cout << i << '\n';
12 }
13 catch (invalid_argument const &e)
14 {
15 cout << "Bad input: std::invalid_argument thrown" << '\n';
16 }
17 catch (out_of_range const &e)
18 {
19 cout << "Integer overflow: std::out_of_range thrown" << '\n';
20 }
21
22 return 0;
23}
1#include <iostream>
2#include <sstream>
3using namespace std;
4int main()
5{
6 string str = "123456";
7 int n;
8 stringstream ( str ) >> n;
9 cout << n; //Output:123456
10 return 0;
11}
1//stoi() : The stoi() function takes a string as an argument and
2//returns its value. Supports C++11 or above.
3// If number > 10^9 , use stoll().
4#include <iostream>
5#include <string>
6using namespace std;
7main() {
8 string str = "12345678";
9 cout << stoi(str);
10}
11