'Why I cant use atoi() function on a "string" instead of the char pointer in C++?

I tried the following code and it is giving me error.

int main() {
    string String = "1235";
    int num = atoi(String);
    cout << num << endl;
    return 0;
}
/*
error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'const char*' for argument '1' to 'int atoi(const char*)'
     int num = atoi(String);
                          ^
mingw32-make.exe[1]: *** [Debug/main.cpp.o] Error 1
mingw32-make.exe: *** [All] Error 2 
*/

But if I use the following code it works perfectly fine.

int main() {
    char* String = "1235";
    int num = atoi(String);
    cout << num << endl;
    return 0;
}
//prints out 1235

I know I can solve my problem using stoi() function.

int main() {
    string String = "1235";
    int num = stoi(String);
    cout << num << endl;
    return 0;
}
//prints out 1235

I can solve my problem by using a char pointer instead of string. But I just want to know why this can't be done by placing string itself into atoi(). How does atoi() work internally?

I just wanna know how does atoi() function work in C++



Solution 1:[1]

Because const char* and std::string are incompatible, the implicit conversion cause error.

If you still want to use std:string:

int main() {
    string String = "1235";
    int num = atoi(String.c_str());
    cout << num << endl;
    return 0;
}

see this ref.

Solution 2:[2]

While std::stoi accepts std::string as input, ::atoi does not.

Note: std::string is a c++ class type, const char* is a basic data type. Although std::string does have a member function .c_str(), which can return its C-Style representation with const char* type.

Protype declarations of std::stoi in <string>:

int stoi( const std::string& str, std::size_t* pos = nullptr, int base = 10 );
int stoi( const std::wstring& str, std::size_t* pos = nullptr, int base = 10);

Protype declaration of ::atoi in <stdlib.h>:

int atoi (const char *__nptr);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 navylover
Solution 2