Linux “to_string”不是“std”的成员?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19122574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:59:46  来源:igfitidea点击:

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

c++linuxstringc++11g++

提问by mueslo

Okay, so I have

好的,所以我有

tmp.cpp:

tmp.cpp:

#include <string>

int main()
{
    std::to_string(0);
    return 0;
}

But when I try to compile I get:

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

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

I'm running g++ version 4.8.1. Unlike all the other references to this error that I found out there, I am notusing MinGW, I'm on Linux (3.11.2).

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

Any ideas why this is happening? Is this standard behaviour and I did something wrong or is there a bug somewhere?

任何想法为什么会发生这种情况?这是标准行为,我做错了什么还是某处有错误?

采纳答案by CS Pei

you may want to specify the C++ version with

您可能想要指定 C++ 版本

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

I don't have gcc 4.8.1 at hand , but in older versions of GCC, you can use

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

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

At least gcc 4.9.2 I believe also support part of C++14 by specifying

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

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

Update: gcc 5.3.0 (I am using the cygwin version) supports both -std=c++14and -std=c++17now.

更新:GCC 5.3.0(我用cygwin的版本)支持-std=c++14-std=c++17现在。

回答by Lasitha Konara

to_string works with the latest C++ versions like version 11. For older versions you can try using this function

to_string 适用于最新的 C++ 版本,如版本 11。对于旧版本,您可以尝试使用此函数

#include <string>
#include <sstream>

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

By adding a template you can use any data type too. You have to include #include<sstream>here.

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