1 #include <iostream>
2 #include <string>
3 #include <vector>
4 #include <fstream>
5 #include <sstream>
6
7 using namespace std;
8
9 string int2str(int number)
10 {
11 string strNumber;
12 int result = abs(number);
13
14 if (result == 0)
15 {
16 strNumber = "0";
17 }
18 else
19 {
20 while (result)
21 {
22 strNumber = (char)(result % 10 + '0' ) + strNumber;
23 result /= 10;
24 }
25 }
26
27 if (number < 0)
28 strNumber = "-" + strNumber;
29
30 return strNumber;
31 }
32
33 int main(int argc, char *argv[])
34 {
35 string strNumber = int2str(-797);
36 cout << strNumber << endl;
37
38 return 0;
39 }
这里是将int转化为string类型,思路是将int型数据除以10得到从而得到每一位。
1 #include <iostream>
2 #include <string>
3 #include <vector>
4 #include <fstream>
5 #include <sstream>
6
7 using namespace std;
8
9 int str2int(const string& strNumber)
10 {
11 if (strNumber.length() == 0)
12 {
13 cout << "Input error!" << endl;
14 return -1;
15 }
16
17 string tmpStr(strNumber);
18 if (tmpStr[0] == '-')
19 tmpStr.assign(tmpStr.begin() + 1, tmpStr.end());
20
21 int number = 0;
22 for (size_t i = 0; i < tmpStr.length(); i++)
23 {
24 number = number * 10 + (tmpStr[i] - '0');
25 }
26
27 if (strNumber[0] == '-')
28 number *= -1;
29
30 return number;
31 }
32
33 int main(int argc, char *argv[])
34 {
35 int number = str2int(string("-70865"));
36 cout << number << endl;
37
38 return 0;
39 }
将string转化为int类型。