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++