C++ is one of the most widely used programming languages and you should learn to code in C++. It is used in multiple domains such as game development, embedded systems, operating systems, IoT devices, etc. Owing to its efficiency and powerful construct, we can do almost everything with C++. Therefore, we might come across situations where we have to convert a number to a string in C++. Since the range of numerical data types is finite, we might want to store large numbers in form of strings.
Another case where we might want to store numbers as strings is when we have categorical data. For example, we represent the class of a student with a number but since it is categorical data, the best practice is to store it as a string. In this article, we will understand the different methods to convert a number to a string. In this article, we discuss how to convert a number to a string in C++.
Taking input into a string in C++
If we want to store a number as a string, we can do so by taking the input directly into a string. When we provide a number as the input to the program through the console, its data type depends on the variable into which it is stored. Therefore, we can declare a string variable for taking a numeric input. In this way, our number will be automatically converted to a string. Let us understand this method with the help of the following C++ code.
#include<iostream>
#include<typeinfo>
using namespace std;
int main()
{
string num;
cout<<"Enter your number"<<endl;
cin>>num;
cout<<"The number is: "<<num<<endl;
cout<<"Data type of number: "<<typeid(num).name()<<endl;
return 0;
}
The output of the code is given below.
Enter your number
123456
The number is: 123456
Data type of number: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
You should note the absurd-looking name of the data type of number. It is the named identifier for the strings in C++. The typeid()
operator is defined in the <typeinfo>
header file. The name() method of the typeid()
operator returns the named identifier of the data type of the object passed to the typeid()
operator. You can visit this link to know more about the typeid()
operator and its name()
method.
Convert a Number to String Using the to_string() method in C++
C++ provides us with multiple methods to convert a number to a string. Another method to do so is to use the inbuilt to_string()
function. The to_string()
function is defined in the ‘std
’ namespace. It takes a number of any data type as the input parameter and returns a string object by converting the number to the string. Since the to_string()
function is defined in many polymorphic forms, it can handle all of the numeric data types such as integers, floating-point numbers, and doubles including negative numbers. For negative numbers, we get the string with a negative sign.
Let us understand the to_string()
function with the help of code.
#include<iostream>
using namespace std;
int main()
{
int num1, num2;
double num3;
cout<<"Enter your numbers\n";
cin>>num1>>num2>>num3;
string str1, str2, str3;
str1 = to_string(num1);
str2 = to_string(num2);
str3 = to_string(num3);
cout<<"Numbers converted to strings are:\n";
cout<<str1<<" "<<str2<<" "<<str3<<endl;
return 0;
}
The output of the above code is given below.
Enter your numbers
123
-123
456.78
Numbers converted to strings are:
123 -123 456.780000
You should note that a double in C++ is internally stored up to the precision of six decimal places. Therefore, the last number is shown up to six decimal places.
Convert a Number to a String Using C++ string Streams
To facilitate the string operations, we are provided with the stringstream
in C++. The stringstream
enables us to read from the string as if we are reading from the console stream. We can also write to the string as if we are writing to the console stream. The stringstream
is defined in the <sstream>
header file. Within the stringstream, we have the str() member function. The str() function converts the current contents of the stream to a string and returns a string object.
The stringstream
can be opened in two different modes. Each of the modes defines the way the stream should operate. The input mode enables us to read using the stream. On the other hand, output mode enables us to write using the stream. We can concatenate both modes using OR (|) operator. By default, the stream is opened in the input as well as the output stream.
Therefore, to convert our number to the string in C++, we shall create a stringstream
and write our number to that stream. We shall then invoke the str()
function of the stream that will return a string object containing our converted number.
Let us see an example code to understand this logic.
#include<iostream>
#include<typeinfo>
#include<sstream>
using namespace std;
int main()
{
int num;
cout<<"Enter the number"<<endl;
cin>>num;
stringstream stream;
stream<<num; //writing number to stream
string str = stream.str();
cout<<"Converted number is: "<<str<<endl;
return 0;
}
Note that we have used the default stringstream
in our example. It means, our stream is open for reading as well as writing.
The output of the above code is given below.
Enter the number
123
Converted number is: 123
Enter the number
-123
Converted number is: -123
Conclusion
We often work around numbers and strings in the programming. Also, we often want to convert numbers to strings and vice versa. It is therefore viable for us to understand the methods for converting numbers to strings. We have understood three different methods that we can use to convert numbers to strings in C++. All three methods can work for any type of number therefore it is a matter of choice for you to choose any of them.
However, you might have observed that each of these methods can be more useful in different situations. For example, if you are taking inputs from the console, you can use the first method and while working with streams and files, you might use the third method. On the other hand, the second method of using the to_string() function is very generic and we can use it anywhere as per our need.
I hope you have enjoyed reading the article. To know more about programming in C++, you can read this article on 2-D arrays in C++. You might also like this article on Binary Tree Traversal Algorithms in C++.
Keep checking for more informative articles.
Donate to Avid Python
Dear reader, If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. Thank you for your support! Best regards, Aditya Founder
If you want to Pay Using UPI, you can also scan the following QR code.