(C++) How to transform 'int' into 'string'  

Posted by Xkram or MarkX


  使用sstream類別庫中的stringstream型態,因為stringstream無論是在 << 中;或 >> 中,都會自動轉型。


1  /*
2  (C) OOMusou 2007 http://oomusou.cnblogs.com
3
4  Filename : int2str_sstream.cpp
5  Compiler : Visual C++ 8.0 / ISO C++
6  Description : Demo the how to convert int to string
7  Release : 01/06/2007 1.0
8  */
9
10 #include <iostream>
11 #include <string>
12 #include <sstream>
13
14 using namespace std;
15
16 string int2str(int &);
17
18 int main(void) {
19     int i = 123;
20     string s;
21     s = int2str(i);
22
23     cout << s << endl;
24 }
25
26 string int2str(int &i) {
27     string s;
28     stringstream ss(s);
29     ss << i;
30
31     return ss.str();
32 }

This entry was posted on Monday, March 12, 2012 and is filed under . You can leave a response and follow any responses to this entry through the Subscribe to: Post Comments (Atom) .

0 comments