关于c ++:编译错误:“ stoi”不是“ std”的成员


Compile error: 'stoi' is not a member of 'std'

我的代码:

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
    std::string test ="45";
    int myint = std::stoi(test);
    std::cout << myint << '
'
;
}

给我编译错误:

1
2
3
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会打印出:

1
gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010


在libstdc ++中,stoistol等的定义以及to_string函数受以下条件的保护:

1
2
#if ((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
     && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))

我以前在一个平台(即android上的Termux)上遇到过这种故障,导致即使x ++ 6.1和C ++ 14标准也无法使用to_string。在那种情况下,我只是做了

1
#define _GLIBCXX_USE_C99 1

在包含任何东西之前,这些功能突然存在。 (您应该将其放在第一个,甚至放在命令行上,而不是放在包含之前,因为另一个标头可能首先包含,然后其包含保护措施将使它无法看到您的宏。)

我没有调查为什么没有首先设置此宏。显然,如果您想让代码真正起作用,这是一个令人担忧的问题(在我的情况下,我并不是特别注意,但是FWIW没问题。)

您应该检查是否未定义_GLIBCXX_USE_C99_GLIBCXX_HAVE_BROKEN_VSWPRINTF(在MinGW上可能是这种情况?)


std :: stoi是C ++ 11函数。您必须使用-std=c++11在g ++和clang ++中都启用它。这是实际问题,而不是链接错误或特定的预处理程序定义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 $ cat test.cxx
#include <iostream>
#include <string>

int main()
{
    std::string test ="45";
    int myint = std::stoi(test);
    std::cout << myint << '
'
;
}
 $ 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++")(未经测试)

1
2
3
#include <cstdlib>

int myInt = std::atoi(test.c_str());


如果使用Cmake进行编译,请添加以下行:

" add_definitions(-std = c ++ 11)"

在find_package命令之后。