How to convert a string to an int in C++

There are certain instances in C++ programming when it is necessary to convert a certain data type to another; one such conversion is from a string to an int.

svg viewer

Let’s have a look at a few of the ways to convert a string to an int:


1. Using the stringstream class

The stringstream class is used to perform input/output operations on string-based streams. The << and >> operators are used to extract data from(<<) and insert data into (>>) the stream. Take a look at the example below:​

#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "100"; // a variable of string data type
int num; // a variable of int data type
// using the stringstream class to insert a string and
// extract an int
stringstream ss;
ss << str;
ss >> num;
cout << "The string value is " << str << endl;
cout << "The integer representation of the string is " << num << endl;
}

2. Using stoi()

The stoi() function takes a string as a parameter and returns the integer representation. Take a look at the example below:

#include <iostream>
#include <string>
using namespace std;
int main() {
// 3 string examples to be used for conversion
string str_example_1 = "100";
string str_example_2 = "2.256";
string str_example_3 = "200 Educative";
// using stoi() on various kinds of inputs
int int_1 = stoi(str_example_1);
int int_2 = stoi(str_example_2);
int int_3 = stoi(str_example_3);
cout << "int_1 : " << int_1 << endl;
cout << "int_2 : " << int_2 << endl;
cout << "int_3 : " << int_3 << endl;
}

3. Using atoi()

The atoi() function is different from the stoi() function in a few ways. First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int, while the stoi() function will simply throw an exception.

Take a look at the​ ​usage of atoi() below:

#include <iostream>
#include <string>
using namespace std;
int main() {
// 3 string examples to be used for conversion
const char* str_example_1 = "100";
const char* str_example_2 = "2.256";
const char* str_example_3 = "200 Educative";
// using stoi() on various kinds of inputs
int int_1 = atoi(str_example_1);
int int_2 = atoi(str_example_2);
int int_3 = atoi(str_example_3);
cout << "int_1 : " << int_1 << endl;
cout << "int_2 : " << int_2 << endl;
cout << "int_3 : " << int_3 << endl;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved