【问题标题】:How do I fix a "no matching function for call to 'atoi'" error?如何修复“调用‘atoi’没有匹配的函数”错误?
【发布时间】:2014-05-10 22:45:57
【问题描述】:

所有迹象都告诉我这是一个非常容易解决的问题,但我无法弄清楚错误告诉我atoi 函数不存在。

C++

#include <iostream>
#include <stdlib.h>

using namespace std;

string line;
int i;

int main() {

    line = "Hello";
    i = atoi(line);
    cout << i;

    return 0;
}


错误

lab.cpp:18:6: error: no matching function for call to 'atoi'
i = atoi(line);
    ^~~~

【问题讨论】:

  • 您应该将#include &lt;stdlib.h&gt; 更改为正确的&lt;cstdlib&gt; 并调用std:: atoi
  • 请不要使用atoi,除非你很疯狂并且实际上更喜欢将错误返回值作为合法结果。
  • @MaxBozzi 这是个好主意,但在这里没有用。
  • @juanchopanza 不,但看起来你已经解决了他的问题 :)
  • 你用的是什么编译器?因为我想记住,有一个损坏的 mingw 版本(与 Code::Blocks 一起默认使用)缺少 atoi 函数。不确定 C::B 是否仍然如此,但可能是这样。如果这是您的问题,您必须手动下载更新的编译器版本并将其添加到 C::B

标签: c++ atoi


【解决方案1】:

atoi 需要 const char*,而不是 std::string。所以传一个:

i = atoi(line.c_str());

或者,使用std::stoi:

i = std::stoi(line);

【讨论】:

    【解决方案2】:

    你必须使用

    const char *line = myString.c_str();
    

    代替:

    std::string line = "Hello";
    

    因为 atoi 不接受 std::string

    【讨论】:

      猜你喜欢
      • 2019-10-09
      • 2019-12-15
      • 2013-05-05
      • 2012-12-28
      • 2015-03-31
      • 1970-01-01
      • 2020-09-13
      相关资源
      最近更新 更多