xxxxxxxxxx
stringstream string_to_int;
string s1="12345";
int n1;
xxxxxxxxxx
int number = std::stoi(string, base); // str to int
int number = std::stoi("100",10); // number = 100
long int number = std::strtol(string, endptr, base); // str to long int
xxxxxxxxxx
int number = std::stoi(string); // str to int
int number = std::stoi("100"); // number = 100
xxxxxxxxxx
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num;
num = std::stoi(str);
std::cout << num;
return 0;
}
xxxxxxxxxx
#include<string>
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
std::cout<<stoi(str1);
xxxxxxxxxx
#include <iostream>
#include <string>
using namespace std;
int main() {
// a string variable named str
string str = "7";
//print to the console
cout << "I am a string " << str << endl;
//convert the string str variable to have an int value
//place the new value in a new variable that holds int values, named num
int num = stoi(str);
//print to the console
cout << "I am an int " << num << endl;
}
xxxxxxxxxx
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "10";
try
{
int i = stoi(s);
cout << i << '\n';
}
catch (invalid_argument const &e)
{
cout << "Bad input: std::invalid_argument thrown" << '\n';
}
catch (out_of_range const &e)
{
cout << "Integer overflow: std::out_of_range thrown" << '\n';
}
return 0;
}
xxxxxxxxxx
// C++ program to demonstrate working of stoi()
// Work only if compiler supports C++11 or above
// Because STOI() was added in C++ after 2011
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1); // type of explicit type casting
int myint2 = stoi(str2); // type of explicit type casting
int myint3 = stoi(str3); // type of explicit type casting
cout << "stoi(\"" << str1 << "\") is " << myint1
<< '\n';
cout << "stoi(\"" << str2 << "\") is " << myint2
<< '\n';
cout << "stoi(\"" << str3 << "\") is " << myint3
<< '\n';
return 0;
}
xxxxxxxxxx
// EXAMPLE
std::string sStringAsString = "789";
int iStringAsInt = atoi( sStringAsString.c_str() );
/* SYNTAX
atoi( <your-string>.c_str() )
*/
/* HEADERS
#include <cstring>
#include <string>
*/
xxxxxxxxxx
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1); // type of explicit type casting
int myint2 = stoi(str2); // type of explicit type casting
int myint3 = stoi(str3); // type of explicit type casting
/* Result
45
3
31337
*/
xxxxxxxxxx
// Both functions work identically though you'll need to use "#include <string>"
atoi( str.c_str() );
stoi( str );