forked from hengqiali/AwesomeCpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
字符串和数字相互转换
52 lines (43 loc) · 1.29 KB
/
字符串和数字相互转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <sstream>
#include <boost/format.hpp>
using namespace std;
int main()
{
/****************** <sstream> stringstream ******************/
//把int转换成字符串,把int和字符串连接起来
int a = 123;
double b = 564.3;
string sa = to_string(a);
string sb = to_string(b);
cout << sa << endl << sb << endl;
stringstream s0;
char s1[] = "789";
string s2("56.5");
string s2_("h q");
s0 << "hello" << 123 << s1 << s2_; //把所有内容读进s0,可以有空格
s0 << s2;
string s3 = s0.str(); //string s3; s0 >> s3;
cout << s3 << endl;
//把string或char*类型的字符串转换成int
double y;
stringstream s7;
s7 << s2;
//s7 << s1;
s7 >> y;
cout << y << endl;
string s4;
while(s0 >> s4) //把s0的所有内容读进s4,读进的过程中自动会在空白符处断开
cout << s4 << endl;
/****************** <boost/format.hpp> boost::format ******************/
//把int和字符串连接起来
string s5 = (boost::format("%1% -- %2% test") % "ad" % 2).str();
cout << s5 << endl;
//字符串转int
string s6("1243");
int x = std::atoi(s6.c_str()); // atol(long), atof(float), atod(double) 等
cout << x << endl;
int xx = stoi(s6);
cout << xx << endl;
return 0;
}