【问题标题】:Parsing int in C++11 - stoi在 C++11 中解析 int - stoi
【发布时间】:2014-02-16 17:08:52
【问题描述】:

我正在尝试获取一个字符串并将其解析为一个 int。我已经阅读了很多答案,似乎使用stoi 是最新的方法。在我看来stoi 使用std,但我得到Function 'stoi' could not be resolved 绝望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;
}

任何想法是什么原因造成的?

更新:

我正在使用 Eclipse。我的标志是:-c -fmessage-length=0 -std=c++11

【问题讨论】:

  • 你忘了告诉我们你的编译器是什么,以及你是如何编译这个程序的。
  • plab 很好找 plab。好眼力!在你的答案中张贴一个大的绿色复选标记
  • 你还没有告诉我们什么编译器,什么版本,或者类似的东西。请养成精确的习惯。
  • 我个人喜欢这种情况下的字符串流。 istringstream iss(five); iss &gt;&gt; number;

标签: c++ parsing c++11 namespaces std


【解决方案1】:

如果您使用的是 GCC 或 MINGW,那么答案如下: std::stoi doesn't exist in g++ 4.6.1 on MinGW

这是一个非标准的 vswprintf 声明的结果 视窗。 GNU 标准库定义 _GLIBCXX_HAVE_BROKEN_VSWPRINTF 在此平台上,这反过来会禁用您尝试使用的转换功能。你可以 在此处阅读有关此问题和宏的更多信息: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37522.

如果您愿意修改随 MinGW 分发的头文件, 您可以通过删除 !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF) 宏在第 2754 行 .../lib/gcc/mingw32/4.6.1/include/c++/bits/basic_string.h,并添加 它回到第 2905 到 2965 行(引用的行 标准::vswprintf)。您将无法使用 std::to_wstring 函数,但许多其他转换函数应该是 可用。

请始终提供平台和编译器信息。

【讨论】:

    【解决方案2】:

    在编译器标志中切换 C++11 支持。 -std=c++11 最近的 gcc。对于 Eclipse,请参阅常见问题解答中的 corresponding question,此 answer 解释了如何摆脱剩余的 Eclipse 警告。

    【讨论】:

    • 非常感谢。有机会知道文件名吗?我现在在 Eclipse 中运行它。
    • @Evorlor:什么文件名?
    • 我实际上并没有在终端中编译它。我在 Eclipse 中编写代码。
    • @plabatut 嗯...谢谢,但这似乎并没有解决问题
    • @Evorlor 请注意,eclipse 是一个 IDE;它实际上并没有编译你的程序(至少不是为了获得可执行文件,对于迂腐的)。为此,它将像在终端上一样调用外部编译器。
    【解决方案3】:

    如果您愿意以另一种方式解析 int,那么使用 STL 算法和 C++11 lambda 表达式怎么样?

    #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;
    }
    

    【讨论】:

    • 好收获!我认为 { int number; istringstream iss("5");问题>>号码; } Brandin 建议的方法更通用、更合适。
    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 2014-08-21
    • 2015-09-07
    • 1970-01-01
    • 2011-09-01
    相关资源
    最近更新 更多