In C++, integer and string represent distinct data types. An integer is primarily employed for numerical values, while a string is utilized to store character sequences. In C++, transforming an integer (int) into a string (std::string) is a frequent task. This conversion is particularly valuable for formatting output, logging, or organizing data for presentation or storage purposes.
There are several methods that can help to convert an int to a string in C++. Some of them are as follows:
- Using std::stringstream
- Using std::to_string (C++11 and later)
- Using Boost or other libraries
- Using sprintf or snprintf (C-style)
Now, we will discuss these methods one by one.
Convert an integer into a string Using Stringstream Class
In C++, the stringstream class is a stream class that is declared in the header file. This stream class is employed for conducting input-output tasks on streams based on strings.
Syntax
It has the following syntax:
std::stringstream ss; // stringstream object
ss << num; // Insert the integer into the stream
std::string str = ss.str();
The following are the operators used to insert or extract the data:
- Operator >>: It extracts the data from the stream.
- Operator <<: It inserts the data into the stream.
Let's understand the concept of operators through an example.
- In the below statement, the << insertion operator inserts the 100 into the stream.
_PRESERVE1__
- In the below statement, the >> extraction operator extracts the data out of the stream and stores it in 'i' variable.
stream1 >> i;
Example to convert int to string Using Stringstream Class
Let's consider an example to showcase the process of converting an integer to a string using the stringstream class in C++.
Example
#include <iostream>
#include<sstream>
using namespace std; //using standard namespace
int main() { //Main Function
int k;
cout<<"Enter an integer value: ";
cin>>k;
stringstream ss;
ss<<k; //insert integer into stream
string s = ss.str();
cout<<"\n"<<"An integer value is: "<<k<<"\n";
cout<<"String representation of an integer value is: "<<s;
}
Output:
Enter an integer value: 45
An integer value is: 45
String representation of an integer value is: 45
Explanation
In this instance, a variable named k is initialized, and the intention is to transform the numerical value of k into a string representation. Subsequently, the stringstream class is employed for the conversion of the integer value of k into a string format.
Convert an integer into a string Using to_string method
In C++, the to_string function takes in an integer as an argument and converts the integer value or another data type value into a string.
Syntax
It has the following syntax:
string to_string(int value);
C++ Example to convert int to string using to_string method
Let's consider an illustration to showcase the process of converting an integer to a string using the to_string function in C++.
Example
#include <iostream>
#include<string>
using namespace std; //using standard namespace
int main() //Main Function
{
int i=11; //intialize integer value
float f=12.3; //intialize integer value
string str= to_string(i);
string str1= to_string(f);
cout<<"string value of integer i is: "<<str<<"\n";
cout<<"string value of f is: "<< str1;
}
Output:
string value of integer i is: 11
string value of f is: 12.300000
Explanation
In this instance, we are exploring the to_string method, which transforms integer and decimal values into their respective string formats. This function offers a straightforward and clear approach for managing conversions from numbers to strings in C++.
Convert an integer into a string Using a boost.lexical cast
In the C++ programming language, the boost.lexical cast offers a casting mechanism called boost.lexical_cast, enabling the conversion of a string value to an integer or another data type, and vice versa.
Syntax
It has the following syntax:
std::string str = boost::lexical_cast<std::string>(integer_variable);
C++ Example to convert an integer to string using a boost.lexical cast
Let's consider an illustration to showcase the process of converting an integer to a string in C++ using boost.lexical_cast.
Example
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
using namespace std; //using standard namespace
using boost::lexical_cast;
int main() //Main Function
{
int i=11; //initialize integer value
string str = boost::lexical_cast<string>(i);
cout<<"string value of integer i is :"<<str<<"\n";
}
Output:
string value of integer i is :11
Explanation
In the previous example, we transformed the 'i' variable's value into a string by employing the lexical_cast function.
Convert an integer into string Using sprintf or snprintf (C-style)
In C++, an alternative method to transform an integer into a string involves utilizing the C-style functions sprintf or snprintf, located in the cstdio header. These functions are components of the C standard library and offer formatted string output. They enable various operations, such as converting integers into character arrays (C-style strings), which can then be further converted into std::string.
Syntax
It has the following syntax:
sprintf(buffer, "%d", num); // Or use snprintf(buffer, sizeof(buffer), "%d", num);
std::string str(buffer);
C++ Example to convert an int to string using sprintf/snprintf
Let's consider a scenario to demonstrate the process of converting an integer to a string using sprintf/snprintf in the C++ programming language.
Example
#include <cstdio>
#include <iostream>
using namespace std; //using standard namespace
int main() { //Main Function
int num = 123; //initialize integer number
char buffer[20];
std::sprintf(buffer, "%d", num);
std::string str = buffer;
std::cout << "Converted string: " << str << std::endl;
return 0;
}
Output:
Converted string: 123
Explanation
In this instance, we employ the sprintf function to change an integer into a C-style string (char) and subsequently assign it to a C++ std::string. This method follows a conventional C-style technique but remains efficient within the C++ context.
When and Why Do We Convert int to string in C++?
In C++, an int is used to store numbers, and a string is used to store text. Sometimes, we need to change a number (int) into text (string). It is helpful when we want to:
- Join the number with other text (concatenation)
- Format the number nicely for display
- Save the number as text in a file
- Show the number on the screen
One method to achieve this in C++ is by leveraging the stringstream class. This class enables us to handle numbers as if they were text. We insert the number into the stream and subsequently retrieve it as a string. This approach proves beneficial when we have the necessity to:
- Send the number as text to a function
- Save it in a data structure that relies on strings
Conclusion
In C++, transforming an integer into a string is a simple task with various methods available, depending on the specific C++ version and project requirements. For contemporary C++ programmers, the preferred and succinct option for converting an integer to a string is by using std::to_string. However, it is beneficial to have knowledge of alternative techniques such as stringstream and sprintf, particularly when dealing with older codebases or platforms that have restricted standard library capabilities.
C++ Convert an Int to String MCQs
1) Which of the following is the most modern and simplest way to convert an int to string in C++11 and later?
- sprintf
- std::to_string
- std::stoi
- atoi
2) What is the main purpose of using stringstream for int-to-string conversion in C++?
- To treat numbers like streams of characters
- To store multiple integers in a string
- To perform mathematical operations on strings
- To convert lowercase to uppercase
a) Handling numbers as sequences of characters enables manipulating numerical data in a more flexible manner.
3) Which of the following methods is used in C-style programming to convert an int to a string?
- std::to_string
- std::stringstream
- boost::lexical_cast
- sprintf
4) Why would a programmer convert an int to a string in C++?
- To perform arithmetic operations
- To use it in a loop
- To display it with other text or save it as text
- To convert it to a float
Option c) is chosen to exhibit the content alongside additional text or to store it as a text file.
5) What does the boost::lexical_cast<std::string>(int) function do in C++?
- Converts a string to integer
- Converts a float to string
- Converts an int to a string
- Converts a character to string