stoi in c++
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << "Converted integer: " << num << std::endl;
return 0;
}
- Include Libraries:
#include <iostream>
: Includes the input/output stream library.#include <string>
: Includes the string library.Declare Main Function:
int main()
: Declares the main function.Declare a String:
std::string str = "123";
: Declares a string variable namedstr
and initializes it with the value "123".Convert String to Integer:
int num = std::stoi(str);
: Uses thestd::stoi
function to convert the stringstr
to an integer and assigns the result to the variablenum
.Output Result:
std::cout << "Converted integer: " << num << std::endl;
: Prints the converted integer to the standard output.Return Statement:
return 0;
: Indicates that the program executed successfully and returns 0 to the operating system.