How to use C++11 std::stoi with gcc?

44,340

Solution 1

#include <iostream>
#include <string>

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

or

#include <iostream>
#include <string>

using namespace std    

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

look at http://en.cppreference.com/w/cpp/string/basic_string/stol

Solution 2

std::stoi is a function at namespace scope, taking a string as its argument:

std::string s = "123";
int i = std::stoi(s);

From the error message, it looks like you expect it to be a member of string, invoked as s.stoi() (or perhaps std::string::stoi(s)); that is not the case. If that's not the problem, then please post the problematic code so we don't need to guess what's wrong with it.

Share:
44,340
Razorfever
Author by

Razorfever

Updated on July 09, 2022

Comments

  • Razorfever
    Razorfever almost 2 years

    Possible Duplicate:
    How to convert a number to string and vice versa in C++

    I am using Qt Creator 2.5.0 and gcc 4.7 (Debian 4.7.2-4). I added "QMAKE_CXXFLAGS += -std=c++11" to .pro file. Everything seems to be OK, I used C++11 std::for_each and so on. But when I included "string" header and wanted to use stoi, i got the following error:

    performer.cpp:336: error: 'std::string' has no member named 'stoi'
    

    I found some questions related to MinGW and one more, to Eclipse CDT and they had their answers. But I use Linux, why it is NOT working here?

  • Razorfever
    Razorfever over 11 years
    Thank you very much. It seems to be quite stupid question, but anyway, I hope it will help someone else not to ask it in future :D
  • Chad Skeeters
    Chad Skeeters over 11 years
    When I compile with g++ -std=c++11, stoi doesn't need the namespace specified like your top example. cppreference.com lists it has being in the std namespace, but has the same example you posted here. How might someone know which members of the std namespace don't need the std qualification?
  • AnT stands with Russia
    AnT stands with Russia over 10 years
    @Chad Skeeters: Without using namespace std, all members of std namespace need std qualification, unless they can be found by argument-dependent name lookup (ADL). ADL is the reason this code compiles without using namespace std and without std::. It is a rather extensive topic, which the margins of this comment are too narrow to contain. Search it, there is a lot of info on the Net.