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

2019-01-20 11:38发布

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?

2条回答
干净又极端
2楼-- · 2019-01-20 11:57
#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

查看更多
Animai°情兽
3楼-- · 2019-01-20 12:12

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.

查看更多
登录 后发表回答