【发布时间】:2011-11-21 12:12:45
【问题描述】:
可能重复:
C++ long to string
Easiest way to convert int to string in C++
我习惯了 Java,我几乎可以在任何东西上使用 .toString(),但我正在尝试 C++ 中的一些问题
我不知道如何将long 值转换为string。
【问题讨论】:
可能重复:
C++ long to string
Easiest way to convert int to string in C++
我习惯了 Java,我几乎可以在任何东西上使用 .toString(),但我正在尝试 C++ 中的一些问题
我不知道如何将long 值转换为string。
【问题讨论】:
您可以使用字符串流:
#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);
【讨论】:
stoi() 和 strtoull() 这样的逆运算在 C++11 中对 std::string 有重载。
#include <string>
#include <sstream>
std::ostringstream ss;
long i = 10;
ss << i;
std::string str = ss.str();
【讨论】:
您可以使用字符串流。
std::ostringstream ss;
ss << aLongNumber;
ss.str()
您使用运算符<<,例如iostream cout 和cin。而你使用str() 方法来获取字符串。
【讨论】: