Error with stoi and debugged with gdb

1.3k views Asked by At

My OS is ubuntu 14.04, laptop, i7.

The g++ version is g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2.

I tried to run a simple code to test stoi:

#include <string>
int main() 
{
   std::string s = "123";
   int i = std::stoi(s);
}

When I compile it with: g++ -g prueba2.cpp, I get:

prueba2.cpp: In function ‘int main()’:
prueba2.cpp:6:12: error: ‘stoi’ is not a member of ‘std’
    int i = std::stoi(s);
            ^

When I debug it twice first with g++ -std=c++0x -g prueba2.cpp (I also tried with -std=c++11) and then with dbg, I got:

enter image description here

Then, I also did a simple search and followed the suggestions made in here1, here2 and here3, and none worked.

Am I doing something silly?

2

There are 2 answers

2
CinchBlue On BEST ANSWER

Yeah, I think you're doing something pretty silly. You probably compiled the first code, which doesn't have the std::cout statement, and you probably executed the compilation steps without -std=c++11 which would result in std::stoi not being included beecause std::stoi is from C++11 and onward. The result is still the old executable which prints out nothing.

Recompile using -std=c++11 and make sure that you saved your file correctly. Your code clearly works.

Note: the vanilla port of GCC of MinGW on Windows is flawed and has a few bugs related to C++11 and onwards; using MinGW-w64, if you ever decide to compile on Windows, can help the problem.

5
mastov On

std::stoi is a C++11 feature. Therefore your code only compiles, if you use the -std=c++11 flags (or the equivalent -std=c++0x flag that you mentioned, which has nothing to do with debugging).

The terminal session you provided also shows that compilation works with those flags and your program runs fine without any problem. If you want to print the parsed result, you can do it like that: std::cout << i << std::endl

If you don't want to use C++11 features, you can use the >> stream operator to parse your string to an int:

stringstream ss(s);
int i;
ss >> n;

But beware: Other than with stoi, you won't get an exception, if your input doesn't contain a valid number. You will have to check the stream's status yourself.