c++ convert const char* to int
#include <iostream>
#include <cstdlib>
int main() {
const char* str = "12345";
int convertedInt = std::atoi(str);
std::cout << "Converted integer: " << convertedInt << std::endl;
return 0;
}
Explanation:
#include <iostream>
: Includes the input-output stream header file for handling input and output streams.#include <cstdlib>
: Includes the C Standard Library header file for functions likestd::atoi()
used for string-to-integer conversion.int main() { ... }
: Entry point of the program.const char str = "12345";
: Declares a pointerstr
of typeconst char
and assigns it the memory address of the string literal"12345"
.int convertedInt = std::atoi(str);
: Uses thestd::atoi()
function to convert the C-style stringstr
to an integer and assigns the result toconvertedInt
.std::cout << "Converted integer: " << convertedInt << std::endl;
: Prints the converted integer value to the standard output.
The program uses std::atoi()
from the C Standard Library to convert a C-style string (const char*
) to an integer in C++.