可能重複:
C++ long to string
Easiest way to convert int to string in C++在字符串C++中轉換Long?
我使用到Java,我可以只使用.toString()
上幾乎所有的東西,但我想在C一些問題++
我無法弄清楚如何使long
的值變成string
。
可能重複:
C++ long to string
Easiest way to convert int to string in C++在字符串C++中轉換Long?
我使用到Java,我可以只使用.toString()
上幾乎所有的東西,但我想在C一些問題++
我無法弄清楚如何使long
的值變成string
。
#include <string>
#include <sstream>
std::ostringstream ss;
long i = 10;
ss << i;
std::string str = ss.str();
您可以使用一個字符串流:
#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);
您可以使用一個字符串流。
std::ostringstream ss;
ss << aLongNumber;
ss.str()
您可以使用運營商<<
像iostream
cout
和cin
。並且您使用str()
方法獲取字符串。
你的意思是'ss << x'? –
爲完整性添加了另一個標準解決方案:)另外,我注意到內聯編輯靜靜地跨越其他人的更改。 –
@RMF:感謝編輯,我不知道!也許無用的日子已經結束了! –