C++

C++字符串转数字

Posted by Liao on 2020-05-19

通过几种方法,把数字字符串转成int输出

stoi(string s)

stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的话则会runtime error!

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
//#include <cstring>
using namespace std;
int main()
{
string s1 = "2147482", s2 = "-214748";
cout << stoi(s1) << endl;
cout << stoi(s2) << endl;
return 0;
}
//2147482
//-214748

atoi( const char* )

而atoi()不会做范围检查,如果超出范围的话,超出上界,则输出上界,超出下界,则输出下界;

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
//#include <cstring>
using namespace std;
int main()
{
string s1 = "2147482", s2 = "-214748";
cout << atoi(s1.c_str()) << endl; //通过c_str()把string转成char*
cout << atoi(s2.c_str()) << endl;
return 0;
}
//2147482
//-214748

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; // 把流的字符串写入int
cout << n <<endl;
return 0;
}

//输出 2147482

能以空格为划分每个字符

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;
}
/*
1
23
#
4
*/