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// EXAMPLE
2std::string sStringAsString = "789";
3int iStringAsInt = atoi( sStringAsString.c_str() );
4
5/* SYNTAX
6atoi( <your-string>.c_str() )
7*/
8
9/* HEADERS
10#include <cstring>
11#include <string>
12*/
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}
1// convert Binary to Decimal in cpp
2#include <bits/stdc++.h>
3using namespace std;
4
5int main(){
6 char ch[] = "111";
7 cout<<stoi(ch , 0 ,2);
8 return 0;
9}