通过几种方法,把数字字符串转成int输出
stoi(string s)
stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <iostream>
using namespace std; int main() { string s1 = "2147482", s2 = "-214748"; cout << stoi(s1) << endl; cout << stoi(s2) << endl; return 0; }
|
atoi( const char* )
而atoi()不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;
1 2 3 4 5 6 7 8 9 10 11 12
| #include <iostream>
using namespace std; int main() { string s1 = "2147482", s2 = "-214748"; cout << atoi(s1.c_str()) << endl; cout << atoi(s2.c_str()) << endl; return 0; }
|
stringstream
定义了三个类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。利用stringstream流的特性,可以把字符串转成数字,数字转成字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream> #include <sstream> using namespace std; int main() { string s1 = "2147482"; int n; stringstream sstream; sstream << s1; sstream >> n; cout << n <<endl; return 0; }
|
能以空格为划分每个字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| int main(){ string s = "1 23 # 4"; stringstream ss; ss<<s; while(ss>>s){ cout<<s<<endl; } return 0; }
|