[英]Compile error: 'stoi' is not a member of 'std'
我的代码:
#include <iostream>
#include <string>
int main()
{
std::string test = "45";
int myint = std::stoi(test);
std::cout << myint << '\n';
}
给我编译错误:
error: 'stoi' is not a member of 'std'
int myint = std::stoi(test);
^
但是,根据这里 ,这段代码应该编译好。 我在我的CMakeLists.txt
文件中使用了行set(CMAKE_CXX_FLAGS "-std=c++11 -O3")
。
为什么不编译?
更新:我正在使用gcc
,并运行gcc --version
打印输出:
gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
在libstdc ++中, stoi
, stol
等的定义以及to_string
函数受到条件的保护
#if ((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
&& !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
我之前在一个平台上遇到过这个故障(即Android上的Termux),导致to_string
即使用g ++ 6.1和C ++ 14标准也无法使用。 在那种情况下,我就是这么做的
#define _GLIBCXX_USE_C99 1
在包括任何东西之前,我们突然发现了这些功能。 (你应该把它放在第一个,甚至放在命令行上,而不是在包含<string>
之前,因为另一个头可能首先包含<string>
,然后它的包含防护将使它不会看到你的宏。)
我没有调查为什么这个宏没有设置在第一位。 显然,如果你想让你的代码实际工作,这是一个令人担忧的问题(在我的情况下,我没有特别的,但FWIW没有问题。)
您应该检查是否_GLIBCXX_USE_C99
没有定义,或者如果_GLIBCXX_HAVE_BROKEN_VSWPRINTF
定义 (这可能是对MinGW的情况?)
std :: stoi是一个C ++ 11函数 。 您必须使用-std=c++11
在g ++和clang ++中启用它。 这是实际问题,而不是链接错误或特定预处理器定义。
$ cat test.cxx
#include <iostream>
#include <string>
int main()
{
std::string test = "45";
int myint = std::stoi(test);
std::cout << myint << '\n';
}
$ g++ -otest test.cxx
test.cxx: In Funktion »int main()«:
test.cxx:7:17: Fehler: »stoi« ist kein Element von »std«
int myint = std::stoi(test);
^
$ g++ -otest test.cxx -std=c++11
$ ./test
45
$
编辑:我刚看到你使用的是c ++ 11。 你确定它正在进入你的编译选项吗? 检查生成的makefile并观察执行的命令是否确定。
您的版本似乎是最新的,所以不应该有问题。 我认为这可能与gcc
有关。 尝试使用g++
。( 最有可能自动链接问题。如果你只是在C ++文件上运行gcc,它就不会像g ++那样“正常工作”。那是因为它不会自动链接到C ++ std库等 )。 我的第二个建议是尝试std::atoi
。
@我已经解决了这个问题。 std::stoi
使用libstdc ++ 。 它是关于GNU标准C ++库 。 在gcc
你必须链接添加-lstdc++
。 但是,在g ++中, libstdc ++是自动链接的。 使用gcc和使用g ++
注意它是如何编译的
使用g ++: g++ -std=c++11 -O3 -Wall -pedantic main.cpp && ./a.out
使用gcc: gcc -std=c++11 -O3 -Wall -pedantic -lstdc++ main.cpp && ./a.out
我认为你应该像set(CMAKE_EXE_LINKER_FLAGS "-libgcc -lstdc++")
一样设置标志set(CMAKE_EXE_LINKER_FLAGS "-libgcc -lstdc++")
(未测试)
#include <cstdlib>
int myInt = std::atoi(test.c_str());
如果您使用Cmake进行编译,请添加以下行:
“add_definitions(-std = C ++ 11)”
在find_package命令之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.