"to_string"不是"std"的成员?

mue*_*slo 40 c++ linux string g++ c++11

好的,我有

tmp.cpp:

#include <string>

int main()
{
    std::to_string(0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我尝试编译时,我得到:

$ g++ tmp.cpp -o tmp
tmp.cpp: In function ‘int main()’:
tmp.cpp:5:5: error: ‘to_string’ is not a member of ‘std’
     std::to_string(0);
     ^
Run Code Online (Sandbox Code Playgroud)

我正在运行g ++版本4.8.1.与我在那里发现的所有其他对此错误的引用不同,我没有使用MinGW,我在Linux(3.11.2)上.

任何想法为什么会这样?这是标准的行为,我做错了什么或某处有错误?

CS *_*Pei 48

您可能希望指定C++版本

g++ -std=c++11 tmp.cpp -o tmp
Run Code Online (Sandbox Code Playgroud)

我手头没有gcc 4.8.1,但在旧版本的GCC中,你可以使用

g++ -std=c++0x tmp.cpp -o tmp
Run Code Online (Sandbox Code Playgroud)

至少gcc 4.9.2我相信通过指定也支持C++ 14的一部分

g++ -std=c++1y tmp.cpp -o tmp
Run Code Online (Sandbox Code Playgroud)

更新:gcc 5.3.0(我正在使用cygwin版本)支持-std=c++14-std=c++17现在.

  • 我也遇到过这个问题,似乎std :: to_string在gcc的标准库(libstdc ++)中不可用,但它在libc ++中可用,它带有LLVM/clang (3认同)

Las*_*ara 20

to_string适用于最新的C++版本,如版本11.对于旧版本,您可以尝试使用此功能

#include <string>
#include <sstream>

template <typename T>
std::string ToString(T val)
{
    std::stringstream stream;
    stream << val;
    return stream.str();
}
Run Code Online (Sandbox Code Playgroud)

通过添加模板,您也可以使用任何数据类型.你必须在#include<sstream>这里包括 .