xxxxxxxxxx
#include <sstream>
using namespace std;
int main()
{
stringstream string_to_int;
string s1="12345";
int n1;
string_to_int<<s1;
//也可以使用string_to_int.str(s1);
//或者 s1=string_to_int.str();
string_to_int>>n1;
cout<<"s1="<<s1<<endl;//s1=12345
cout<<"n1="<<n1<<endl;//n1=12345
}
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
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string str = "123456";
int n;
stringstream ( str ) >> n;
cout << n; //Output:123456
return 0;
}
xxxxxxxxxx
//stoi() : The stoi() function takes a string as an argument and
//returns its value. Supports C++11 or above.
// If number > 10^9 , use stoll().
#include <iostream>
#include <string>
using namespace std;
main() {
string str = "12345678";
cout << stoi(str);
}
xxxxxxxxxx
// For C++11 and later versions
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
// Output
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337
xxxxxxxxxx
int number = std::stoi(string); // str to int
int number = std::stoi("100"); // number = 100
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<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>
int main() {
std::string str = "12345";
int num;
num = std::stoi(str);
std::cout << num;
return 0;
}
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;
}