Home > Software engineering >  Why I cant use atoi() function on a "string" instead of the char pointer in C ?
Why I cant use atoi() function on a "string" instead of the char pointer in C ?

Time:02-11

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

CodePudding user response:

While std::stoi could receive std::string as input, ::atoi could not.

Note: std::string is a c class, const char* is a 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);

CodePudding user response:

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.

  • Related