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

"to_string" isn't a member of "std"?

本文关键字:成员 std 不是 to string      更新时间:2023-10-16

好的,所以我有

TMP.cpp:

#include <string>
int main()
{
    std::to_string(0);
    return 0;
}

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

$ 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);
     ^

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

知道为什么会这样吗?这是标准行为,我做错了什么还是某处有错误?

您可能

希望指定C++版本

g++ -std=c++11 tmp.cpp -o tmp

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

g++ -std=c++0x tmp.cpp -o tmp

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

g++ -std=c++1y tmp.cpp -o tmp

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

to_string适用于

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

#include <string>
#include <sstream>
template <typename T>
std::string ToString(T val)
{
    std::stringstream stream;
    stream << val;
    return stream.str();
}

通过添加模板,您也可以使用任何数据类型。您必须在此处包含#include<sstream>