C++ 如何修复“没有匹配的函数调用‘atoi’”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23587090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:29:45  来源:igfitidea点击:

How do I fix a "no matching function for call to 'atoi'" error?

c++atoi

提问by nipponese

All indications tell me this is a ridiculously easy problem to solve, but I can't figure out error telling me the atoifunction doesn't exist.

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

C++

C++

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

using namespace std;

string line;
int i;

int main() {

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

    return 0;
}



Error

错误

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

回答by juanchopanza

atoiexpects const char*, not an std::string. So pass it one:

atoi预计const char*,而不是std::string. 所以通过它:

i = atoi(line.c_str());

Alternatively, use std::stoi:

或者,使用std::stoi

i = std::stoi(line);

回答by Nassim

You have to use

你必须使用

const char *line = myString.c_str();

instead of:

代替:

std::string line = "Hello";

since atoi won't accept an std::string

因为 atoi 不会接受 std::string