2011-09-20 108 views

回答

0
#include <string> 
#include <sstream> 

std::ostringstream ss; 
long i = 10; 
ss << i; 
std::string str = ss.str(); 
9

您可以使用一個字符串流:

#include <sstream> 
#include <string> 

long x; 
// ... 
std::ostringstream ss; 
ss << x; 

std::string result = ss.str(); 

或者您可以使用Boost的lexical_cast

#include <boost/lexical_cast.hpp> 
std::string s = boost::lexical_cast<std::string>(x); 

我認爲這是一個common opinion該語言的這一方面不盡可能優雅。

在新的C++ 11,事情更容易一點,你可以使用std::to_string()功能:

#include <string> 
std::string s = std::to_string(x); 
+0

你的意思是'ss << x'? –

+0

爲完整性添加了另一個標準解決方案:)另外,我注意到內聯編輯靜靜地跨越其他人的更改。 –

+0

@RMF:感謝編輯,我不知道!也許無用的日子已經結束了! –

0

您可以使用一個字符串流。

std::ostringstream ss; 
ss << aLongNumber; 
ss.str() 

您可以使用運營商<<iostreamcoutcin。並且您使用str()方法獲取字符串。