c++中的STL在企业的笔试,面试中有一些常见的技巧,string和int的相互转换用的比较多

int转string

to_string()

1
2
3
4
5
6
7
8
9
10
int main() {
string pi = "pi is " + to_string(3.1415926);
float val = 8.967;
string num = to_string(val);
string perfect = to_string(1+2+4+7+14) + " is a perfect number";

cout << pi << "\n";
cout << num << "\n";
cout << perfect << "\n";
}

输出结果:

1
2
3
pi is 3.141593
8.967000
28 is a perfect number

sstream

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstdio>
#include <cstring>
#include <sstream>

using namespace std;

int main() {
ostringstream os;
int i = 12;
os << i;
cout << "the data is " + os.str() << endl;
}

输出结果:

1
the data is 12

string转int

使用stoi/stol/stoll

1
2
3
4
5
6
7
8
9
10
11
12
int stoi (const string&  str, size_t* idx = 0, int base = 10);


idx:
Pointer to an object of type size_t,
whose value is set by the function to position of the
next character in str after the numerical value.
This parameter can also be a null pointer,
in which case it is not used.

idx获取string中,isdigit(str[i])
所在位置的next位置值

方法如下:

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
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int main() {
string str_dec = "2001, A Space Odyssey";
string str_hex = "40c3";
string str_bin = "-10010110001";
string str_auto = "0x7f";

string::size_type sz;

// intention: 解引用
// int *p = &a;

int i_dec = stoi(str_dec, &sz);
int i_hex = stoi(str_dec, nullptr, 16);
int i_bin = stoi(str_bin, nullptr, 2);
int i_auto = stoi(str_auto, nullptr, 0);

cout << str_dec << ": " << i_dec << "and [ " << str_dec.substr(sz) << "]\n";
cout << str_hex << ": " << i_hex << "\n";
cout << str_bin << ": " << i_bin << "\n";
cout << str_auto << ": " << i_auto << "\n";
}

结果:

1
2
3
4
2001, A Space Odyssey: 2001and [ , A Space Odyssey]
40c3: 8193
-10010110001: -1201
0x7f: 127

atoi()

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

int main() {
string s = "12";
int a = atoi(s.c_str());
cout << a << endl;
}

sstream

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstdio>
#include <cstring>
#include <sstream>

using namespace std;

int main() {
istringstream is("12");
int i;
is >> i;
cout << i << endl;
}