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
.
Let’s have a look at a few of the ways to convert a string
to an int
:
stringstream
classThe 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 typeint num; // a variable of int data type// using the stringstream class to insert a string and// extract an intstringstream ss;ss << str;ss >> num;cout << "The string value is " << str << endl;cout << "The integer representation of the string is " << num << endl;}
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 conversionstring str_example_1 = "100";string str_example_2 = "2.256";string str_example_3 = "200 Educative";// using stoi() on various kinds of inputsint 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;}
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 conversionconst 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 inputsint 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