C++ atoi Function: Convert String to Integer
The atoi function in C++ is used to convert a string into an integer. It takes a pointer to a null-terminated string and returns the corresponding integer value. If the string cannot be converted into an integer, the atoi function will return 0.
Here is an example using the atoi function:
#include <iostream>
#include <cstdlib>
int main() {
const char* str = "12345";
int num = std::atoi(str);
std::cout << "Converted number: " << num << std::endl;
return 0;
}
The output result is:
Converted number: 12345
It is important to note that if there are non-numeric characters in the string, the atoi function will stop converting when it encounters the first non-numeric character. Additionally, if the integer represented by the string exceeds the range of the int data type, the atoi function will return an undefined value. Therefore, for practical applications, it is recommended to use safer and more powerful string conversion functions such as std::stoi or std::stringstream.