4

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?

Community
  • 1
  • 1
Razorfever
  • 210
  • 2
  • 4
  • 11

2 Answers2

4
#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

aldo.roman.nurena
  • 1,323
  • 12
  • 26
  • 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 – Razorfever Nov 27 '12 at 18:30
  • 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? – Chad Skeeters Jan 25 '13 at 15:23
  • 2
    @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. – AnT stands with Russia Mar 04 '14 at 18:23
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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644