Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

atoi

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

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);
    ^~~~
like image 597
nipponese Avatar asked May 10 '14 22:05

nipponese


2 Answers

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

i = atoi(line.c_str());

Alternatively, use std::stoi:

i = std::stoi(line);
like image 185
juanchopanza Avatar answered Sep 28 '22 01:09

juanchopanza


You have to use

const char *line = myString.c_str();

instead of:

std::string line = "Hello";

since atoi won't accept an std::string

like image 43
Nassim Avatar answered Sep 28 '22 00:09

Nassim