Convert String to Integer
Convert String to Integer in C++ (5 Programs)
BeginnerTopic: String Conversion Programs
C++ Convert String to Integer Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
string str = "12345";
// Method 1: Using stoi()
int num1 = stoi(str);
// Method 2: Using stringstream
stringstream ss(str);
int num2;
ss >> num2;
cout << "String: " << str << endl;
cout << "Integer (method 1): " << num1 << endl;
cout << "Integer (method 2): " << num2 << endl;
return 0;
}Output
String: 12345 Integer (method 1): 12345 Integer (method 2): 12345
Understanding Convert String to Integer
This program demonstrates 5 different methods to convert a string to an integer: using stoi(), stringstream, atoi(), sscanf(), and manual conversion.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.