Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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
like image 791
Karnivaurus Avatar asked Jun 26 '16 00:06

Karnivaurus


1 Answers

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?)

like image 80
Nick Matteo Avatar answered Oct 13 '22 12:10

Nick Matteo