To convert a string to an integer in C++, you can use the stoi
function (available in C++11 and later) or use stringstream
. Below are examples for both approaches:
Using stoi
(C++11 and later):
#include <iostream>
#include <string>
int main() {
std::string str = "12345";
int num = std::stoi(str); // Convert string to int
std::cout << "Converted number: " << num << std::endl;
return 0;
}
Using stringstream
:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string str = "12345";
std::stringstream ss(str);
int num;
ss >> num; // Convert string to int using stringstream
std::cout << "Converted number: " << num << std::endl;
return 0;
}
Both methods work well, but stoi
is more straightforward and recommended for simplicity.