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 <sstream>
3
4using namespace std;
5
6int main()
7{
8 string s = "999";
9
10 stringstream degree(s);
11
12 int x = 0;
13 degree >> x;
14
15 cout << "Value of x: " << x;
16}
1// stoi example
2#include <iostream> // std::cout
3#include <string> // std::string, std::stoi
4
5int main ()
6{
7 std::string str_dec = "2001, A Space Odyssey";
8 std::string str_hex = "40c3";
9 std::string str_bin = "-10010110001";
10 std::string str_auto = "0x7f";
11
12 std::string::size_type sz; // alias of size_t
13
14 int i_dec = std::stoi (str_dec,&sz);
15 int i_hex = std::stoi (str_hex,nullptr,16);
16 int i_bin = std::stoi (str_bin,nullptr,2);
17 int i_auto = std::stoi (str_auto,nullptr,0);
18
19 std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
20 std::cout << str_hex << ": " << i_hex << '\n';
21 std::cout << str_bin << ": " << i_bin << '\n';
22 std::cout << str_auto << ": " << i_auto << '\n';
23
24 return 0;
25}