1. 程式人生 > 實用技巧 >C++字串型數字與int型數字的轉換

C++字串型數字與int型數字的轉換

1、string-->int

1.1 C++風格--流

1 include<sstream>
2 
3 stringstream stream;
4 int num = 0;
5 string text("123");
6 stream << text;
7 stream >> num;
8 stream.clear();//轉換後字串還保留在流中,需使用手動清空

1.2 C風格--atoi()函式

int number = 0;
string text = "123";
number = atoi(text.c_str());

2、int-->string

2.1 to_string()函式

string num1 = "1234" + to_string(456);

to_string()函式的實現如下:

 1 //實現to_string函式
 2 #include<iostream>
 3 #include<string>
 4 using namespace std;
 5 #define max 100
 6 string to_String(int n)
 7 {
 8     int m = n;
 9     char s[max];
10     char ss[max];
11     int i=0,j=0;
12 if (n < 0)// 處理負數 13 { 14 m = 0 - m; 15 j = 1; 16 ss[0] = '-'; 17 } 18 while (m>0) 19 { 20 s[i++] = m % 10 + '0'; 21 m /= 10; 22 } 23 s[i] = '\0'; 24 i = i - 1; 25 while (i >= 0) 26 { 27 ss[j++] = s[i--]; 28 }
29 ss[j] = '\0'; 30 return ss; 31 } 32 33 int main() 34 { 35 cout << "請輸入整數:"; 36 int m; 37 cin >> m; 38 string s = to_String(m) + "abc"; 39 cout << s << endl; 40 system("pause"); 41 return 0; 42 }

2.2 字元流

1  int aa = 30;
2  stringstream ss;
3  ss<<aa; 
4  string s1 = ss.str();
5  cout<<s1<<endl; // 30

轉載自:C++ int與string的互相轉換(含原始碼實現)