Error stoi is not a member of std

While trying to compile some programms, found 2 times error about ‘stoi’ is not a member of ‘std’. There is simple test case: #include #include #include ...

Found today that most of those kind of functions give the same «not a member of std» , for example those ones too:

stoi
stod
stof
stoul
stol

What interesting, is that if we check gcc includes like:

includec++8.2.0bitsbasic_string.h
or
includec++8.2.0extvstring.h we can find there something like:

namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

#if _GLIBCXX_USE_C99_STDLIB
  // 21.4 Numeric Conversions [string.conversions].
  inline int
  stoi(const __vstring& __str, std::size_t* __idx = 0, int __base = 10)
  { return __gnu_cxx::__stoa<long, int>(&std::strtol, "stoi", __str.c_str(),
					__idx, __base); }

  inline long
  stol(const __vstring& __str, std::size_t* __idx = 0, int __base = 10)
  { return __gnu_cxx::__stoa(&std::strtol, "stol", __str.c_str(),
			     __idx, __base); }

  inline unsigned long
  stoul(const __vstring& __str, std::size_t* __idx = 0, int __base = 10)
  { return __gnu_cxx::__stoa(&std::strtoul, "stoul", __str.c_str(),
			     __idx, __base); }

  inline long long
  stoll(const __vstring& __str, std::size_t* __idx = 0,	int __base = 10)
  { return __gnu_cxx::__stoa(&std::strtoll, "stoll", __str.c_str(),
			     __idx, __base); }

  inline unsigned long long
  stoull(const __vstring& __str, std::size_t* __idx, int __base = 10)
  { return __gnu_cxx::__stoa(&std::strtoull, "stoull", __str.c_str(),
			     __idx, __base); }

  // NB: strtof vs strtod.
  inline float
  stof(const __vstring& __str, std::size_t* __idx = 0)
  { return __gnu_cxx::__stoa(&std::strtof, "stof", __str.c_str(), __idx); }

  inline double
  stod(const __vstring& __str, std::size_t* __idx = 0)
  { return __gnu_cxx::__stoa(&std::strtod, "stod", __str.c_str(), __idx); }

  inline long double
  stold(const __vstring& __str, std::size_t* __idx = 0)
  { return __gnu_cxx::__stoa(&std::strtold, "stold", __str.c_str(), __idx); }
#endif // _GLIBCXX_USE_C99_STDLIB 

So , kind of should works when we use _GLIBCXX_USE_C99_STDLIB which we can se in the
include/c++/8.2.0/bits/c++config.h. But it didn’t sadly.

In other words, it seems that those «not a member» errors not errors of newlib, but errors of includes provided with gcc on our side.

Topic: Error stoi is not a member of std  (Read 44235 times)

According to http://en.cppreference.com/w/cpp/string/basic_string/stol, std::stoi is part of <string>, but when I try to compile the following code:

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "45";
    std::string str2 = "3.14159";
    std::string str3 = "31337 with words";
    std::string str4 = "words and 2";

    //The error occurs on the next line
    int myint1 = std::stoi(str1);
    int myint2 = std::stoi(str2);
    int myint3 = std::stoi(str3);

    std::cout << "std::stoi("" << str1 << "") is " << myint1 << 'n';
    std::cout << "std::stoi("" << str2 << "") is " << myint2 << 'n';
    std::cout << "std::stoi("" << str3 << "") is " << myint3 << 'n';
}

I get the error «error: ‘stoi’ is not a member of ‘std'»

I did some Googling and found that I apparently need the -std=c++11 flag to enable this feature, but I have this checkbox checked in my GNU GCC Compiler page, as follows:

Can anybody shed some more light on this issue for me please?

Using Code::Blocks 12.11 with mingw32-gcc (tdm-1) 4.7.1


Logged


« Last Edit: March 11, 2014, 02:39:27 pm by stahta01 »


Logged

C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.

When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org


Thanks for the reply.

Here is the Debugged Build Log

————— Build: Debug in Stoi Example (compiler: GNU GCC Compiler)—————

mingw32-g++.exe -Wall -fexceptions  -g  -std=c++11    -c «Z:stuffC++ ProjectsLesson 10Stoi Examplemain.cpp» -o objDebugmain.o
Z:stuffC++ ProjectsLesson 10Stoi Examplemain.cpp: In function ‘int main()’:
Z:stuffC++ ProjectsLesson 10Stoi Examplemain.cpp:12:18: error: ‘stoi’ is not a member of ‘std’
Z:stuffC++ ProjectsLesson 10Stoi Examplemain.cpp:13:18: error: ‘stoi’ is not a member of ‘std’
Z:stuffC++ ProjectsLesson 10Stoi Examplemain.cpp:14:18: error: ‘stoi’ is not a member of ‘std’
Process terminated with status 1 (0 minutes, 0 seconds)
3 errors, 0 warnings (0 minutes, 0 seconds)

I was under the impression that I had posted the exact error message, which is «error: ‘stoi’ is not a member of ‘std'», but thanks for the tip.


Logged


« Last Edit: March 11, 2014, 03:15:31 pm by stahta01 »


Logged

C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.

When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org


Thank you :)


Logged


stoi is not a member of std?

I am using code::blocks version 13.12 and tried to compile this code.

1
2
3
4
5
#include <string>
int main(){
    std::string s = "42";
    int i = std::stoi(s);
}

It give me an error saying that ‘stoi’ is not a member of std, though I am sure that it is, in C++11.
I have also enabled the C++11 in the compiler flag.
Googling this yielded some results saying that MinGW does not support stoi,to_string() and such string-numeric conversion functions. Is there any other compiler I can use which supports C++11 as much as MinGW?
I am using Windows 7 32bit.
P.S it runs fine on http://cpp.sh

Last edited on

You could use Visual Studio.

It’s really good, but does not support C++11 as much as MinGW. Moreover, it looks horrible for C++ coding. Very less auto completion compared to Code blocks.

Latest versions of MinGW.
Visual Studio compilers.

MiiNiPaa, I didn’t understand your post, can you elaborate a little bit?
Do you mean that latest versions of MinGW, fixed the stoi(),.. issues?

Last edited on

I’ve never used Code Blocks but VS can auto complete pretty much anything that intellisense picks up. I’m using VS 2013 Professional so it may be different on different versions.

Last edited on

I heard that visual C++ does not support `constexpr` fully. And `initializer_list` too.

Is LLVM a compiler like GCC?

Last edited on

initiaizer_list’s are supported. constexpr however is not.

> I heard that visual C++ does not support `constexpr` fully. And `initializer_list` too.

The current version of the Microsoft compiler does not support

constexpr

It has complete support for initializer lists.
For other C++11 features, see: http://msdn.microsoft.com/en-us/library/hh567368.aspx

> Is LLVM a compiler like GCC?

clang++ is the C++ compiler from LLVM. http://clang.llvm.org/
libc++ is their implementation of the standard C++ library (not available on Windows): http://libcxx.llvm.org/

That means I can’t use it on windows? :O

> That means I can’t use it on windows?

You can use the LLVM compiler (clang++) with the Microsoft library.

You would get a compiler that is somewhat better than than the GNU compiler, and a library that is a lot better than the GNU library.

You can use the LLVM compiler (clang++) with the Microsoft library.

You would get a compiler that is somewhat better than than the GNU compiler

Cool, thanks a lot.

So What I have to do is just install Visual studio express, and clang++?
Is there any tutorial for this?
Will using another compiler have any effect on the VS debugger?

 
and a library that is a lot better than the GNU library.

Why do you say it is better? It does not support C++11 as much as GCC.

VS has subpar support for core language features. Standard library is more or less complete (and it works better on Windows than libstdc++)
http://msdn.microsoft.com/en-us/library/hh567368.aspx
Scroll to Standard Library Features. Note that almost all defects were fixed in VS2012 and now as article states:

As for the C++11 Standard Library, we don’t have a pretty comparison table of features, but Visual C++ in Visual Studio 2012 implemented it, with two exceptions. First, when a library feature depended on functionality that was missing in the compiler, it was either simulated—for example, simulated variadic templates for make_shared<T>()—or it wasn’t implemented. (There were only a few cases—most notably, <initializer_list>—which are now fully implemented in Visual C++ in Visual Studio 2013.) With very few exceptions, C99 has been implemented in Visual C++ in Visual Studio 2013 and C++ wrapper headers provided.

Hmm, Ok. I am away from my desktop(Which has visual studio) right now. But I will check it again when I get home after some days. I will update the topic then. :)

> It does not support C++11 as much as GCC

GNU libstdc++ has truly vast expanses of non-conformance (on all platforms).

IMHO, while a lot of it can be tolerated, these are show-stoppers:

Non-conforming

std::basic_string

(suffers from the mad-cow disease).

Non-conforming

std::list<>

(not an allocator-aware container, O(N)

size()

)

Virtually no support for localization (missing standard code conversion facets). On non-linux platforms, there are no locales either (other than the classic and default locales).

Broken C++11 thread-safety.

Ok, I got visual studio professional and Visual assist X trials, and I am not going to go back to code blocks again. Previously visual studio’s syntax highlighting and all was not very good but visual assist made it a 10000X better then code blocks.

Anyway, I will use Visual C++ compiler even if it does not fully support C++11 right now. Thanks for the suggestions.

P.S it supports stoi as well :).

Last edited on

Topic archived. No new replies allowed.

Мой код:

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

Однако согласно Вот, этот код должен хорошо скомпилироваться. Я использую линию set(CMAKE_CXX_FLAGS "-std=c++11 -O3") в моем CMakeLists.txt файл.

Почему он не компилируется?


Обновление: я использую gccи работает gcc --version распечатывает:

gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010

10

Решение

В libstdc ++ определения stoi, stolи т. д., а также to_string функции, охраняются условием

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

Я имел этот сбой на одной платформе раньше (а именно Termux на Android), в результате чего to_string недоступно даже с g ++ 6.1 и стандартом C ++ 14. В этом случае я просто сделал

#define _GLIBCXX_USE_C99 1

прежде чем включать что-нибудь, и вуаля, вдруг функции существовали. (Вы должны поставить это сначала, или даже в командной строке, а не только перед включением <string>потому что другой заголовок может включать <string> сначала, а затем включенные охранники не дадут ему увидеть ваш макрос.)

Я не исследовал, почему этот макрос не был установлен в первую очередь. Очевидно, это повод для беспокойства, если вы хотите, чтобы ваш код действительно работал (в моем случае я не особенно, но FWIW проблем не было).

Вы должны проверить, если _GLIBCXX_USE_C99 не определено, или если _GLIBCXX_HAVE_BROKEN_VSWPRINTF является определены (что может быть в случае с MinGW?)

13

Другие решения

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
$

редактировать: я только что увидел, что вы использовали с ++ 11. Вы уверены, что это входит в ваши параметры компиляции? Проверьте сгенерированный make-файл и проследите за выполнением команд, чтобы быть уверенными.

6

Ваша версия выглядит актуальной, поэтому проблем быть не должно. Я думаю, что это может быть связано с gcc, Пытаться g++ вместо.(Скорее всего, автоматически связать проблему. Если вы просто запустите gcc для файла C ++, он не будет «просто работать», как это делает 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++") (Не испытано)

#include <cstdlib>

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

3

Понравилась статья? Поделить с друзьями:
  • Error steamworksauthfail among us как исправить
  • Error steamworks auth fail among us как исправить
  • Error steam upload cloud tabletop
  • Error steam read download tabletop simulator
  • Error steam must be running to play this game farming simulator 2019