Parsing int in C++11 - stoi

£可爱£侵袭症+ 提交于 2021-02-05 10:59:05

问题


I am trying to take a string and parse it into an int. I have read the many answers out there, and it seems that using stoi is the most up-to-date way. It appears to me that stoi uses std, but I am getting Function 'stoi' could not be resolved despitre using namespace std;

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include<stdlib.h>

using namespace std;

int main(int argc, char* argv[]) {

    string line = "";
    string five = "5";
    int number = stoi(five); //Error here with stoi
    return 0;
}

Any ideas what is causing this?

Update:

I am using Eclipse. My flags are: -c -fmessage-length=0 -std=c++11


回答1:


Toggle on C++11 support in your compiler flags. -std=c++11 for a recent gcc. For Eclipse, please refer to the corresponding question in the FAQ and this answer explains how to get rid of the remaining Eclipse warning.




回答2:


If you are using GCC or MINGW, then this is the answer: std::stoi doesn't exist in g++ 4.6.1 on MinGW

This is a result of a non-standard declaration of vswprintf on Windows. The GNU Standard Library defines _GLIBCXX_HAVE_BROKEN_VSWPRINTF on this platform, which in turn disables the conversion functions you're attempting to use. You can read more about this issue and macro here: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37522.

If you're willing to modify the header files distributed with MinGW, you may be able to work around this by removing the !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF) macro on line 2754 of .../lib/gcc/mingw32/4.6.1/include/c++/bits/basic_string.h, and adding it back around lines 2905 to 2965 (the lines that reference std::vswprintf). You won't be able to use the std::to_wstring functions, but many of the other conversion functions should be available.

Please always provide platform and compiler information.




回答3:


If you are amenable to parsing an int another way, how about using an STL algorithm and a C++11 lambda expression?

#include <algorithm>
#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "12345";

    int num = 0;

    for_each(str.begin(), str.end(), [&num](char c){ num = 10 * num + (c - '0');  });

    cout << str << " = " << num << endl;
}


来源:https://stackoverflow.com/questions/21354142/parsing-int-in-c11-stoi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!