string to int in c++
Certainly! To convert a string to an integer in C++, you can use the std::stoi
function. Here's an example with explanations for each step:
#include <iostream>
#include <string>
int main() {
std::string str = "12345"; // Define a string containing the number "12345"
int convertedInt = std::stoi(str); // Convert the string to an integer using std::stoi
std::cout << "String: " << str << std::endl; // Output the original string
std::cout << "Converted Integer: " << convertedInt << std::endl; // Output the converted integer
return 0;
}
#include <iostream>
and#include <string>
: Include necessary libraries for input/output and string manipulation.std::string str = "12345";
: Define a string variablestr
containing the characters "12345".int convertedInt = std::stoi(str);
: Usestd::stoi
to convert the stringstr
to an integer and store it in the variableconvertedInt
.std::cout << "String: " << str << std::endl;
: Output the original stringstr
.std::cout << "Converted Integer: " << convertedInt << std::endl;
: Output the converted integerconvertedInt
.return 0;
: End the program execution.
This code snippet demonstrates how to convert a string representing a number to an integer using std::stoi
in C++.