C++ String to int and vice-versa
In this tutorial, we will learn how to convert string to int and vice versa with the help of examples.
string to int Conversion
We can convert string
to int
in multiple ways. The simplest way to do this is by using the std::stoi()
function. It is introduced in C++ language in C++11 version.
Example 1: C++ string to int Using stoi()
// C++ string to int Using stoi() method
#include <iostream>
#include <string>
int main() {
std::string str = "20";
int age;
// using stoi() to store the value of str1 into x
age = std::stoi(str);
std::cout << age;
return 0;
}
Output
20
Example 2: char Array to int Using atoi()
We can convert a char
array to int
using the std::atoi()
function. The atoi()
function is defined in the cstdlib
header file.
For Example :-
// Example: C++ char Array to int Using atoi() method
#include <iostream>
// cstdlib is needed for atoi()
#include <cstdlib>
using namespace std;
int main() {
// declaring and initializing character array
char str[] = "20";
int age = std::atoi(str);
std::cout << "age = " << age;
return 0;
}
Output
age = 20
To learn other ways of converting strings to integers, Please visit Different Ways to Convert C++ string to int.
C++ int to string Conversion
We can convert int
to string
using the C++11 std::to_string()
function. For older versions of C++, we can use std::stringstream
objects.
Example 3: C++ int to string Using to_string()
This function accepts a number (can be any data type) and returns the number in the desired string.
//Example: C++ int to string Using to_string() method
#include <iostream>
#include <string>
using namespace std;
int main() {
int age = 20;
std::string str = to_string(age);
std::cout << str;
return 0;
}
Output
20
Example 4: C++ int to string Using stringstream
In this method, stringstream declares a stream object which first insert a number, as a stream into object and then uses str() to follow internal conversion of number to string.
#include <iostream>
#include<string>
#include<sstream> // for using stringstream method
using namespace std;
int main() {
int age = 20;
// creating stringstream object ss
std::stringstream ss;
// assigning the value of age to ss
ss << age;
// initializing string variable with the value of ss
// and converting it to string format with str() function
std::string str = ss.str();
std::cout << str;
return 0;
}
Output
20
Recommended Tutorials:
To know about converting a string to float/double, visit C++ string to float, double and Vice-versa
We hope that this tutorial helped you develop better understanding of the concept of String to int in C++.
Keep Learning : )