My code:
#include <iostream>
#include <string>
int main()
{
std::string test = "45";
int myint = std::stoi(test);
std::cout << myint << '\n';
}
Gives me the compile error:
error: 'stoi' is not a member of 'std'
int myint = std::stoi(test);
^
However, according to here, this code should compile fine. I am using the line set(CMAKE_CXX_FLAGS "-std=c++11 -O3")
in my CMakeLists.txt
file.
Why is it not compiling?
Update: I am using gcc
, and running gcc --version
prints out:
gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
In libstdc++, the definitions of stoi
, stol
, etc., as well as the to_string
functions, are guarded by the condition
#if ((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
&& !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
I have had this fail on one platform before (namely Termux on Android), resulting in to_string
not being available even with g++ 6.1 and the C++14 standard. In that case, I just did
#define _GLIBCXX_USE_C99 1
before including anything, and voilà, suddenly the functions existed. (You should put this first, or even on the command line, rather than just before including <string>
, because another header may include <string>
first, and then its include guards will keep it from ever seeing your macro.)
I did not investigate why this macro wasn't set in the first place. Obviously this is a cause for concern if you want your code to actually work (in my case I didn't particularly, but FWIW there were no problems.)
You should check if _GLIBCXX_USE_C99
is not defined, or if _GLIBCXX_HAVE_BROKEN_VSWPRINTF
is defined (which may be the case on MinGW?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With