Convert Long to String in C++ | (3 ways)

In this article, we will learn about three different ways to convert a long to a string in C++ i.e.

  1. Using to_string() function
  2. Using stingstream
  3. Using Boost’s lexical_cast() function.

Let’s discuss them one by one.

Convert long to string using to_string()

C++ provides a function std::to_string() for converting values of different types to string type. We can use this to convert a long to string. For example,

#include <iostream>
#include <string>

using namespace std;

int main()
{
    long num = 102612;

    // Convert long to string 
    string num_str = to_string(num);

    cout<<num_str<<endl;

    return 0;
}

Output:

102612

We passed a long to the to_string() function, and it converted the given long to a string and returned the string object. If you pass a negative long to the to_string(), it will convert to a string with a minus symbol.

Convert long to string using stringstream in C++

C++ provides a class stringstream, which provides a stream-like functionality. We can insert different types of elements in stringstream and get a final string object from the stream. Check out this example,

#include <iostream>
#include <string>
#include<sstream>  

using namespace std;

int main()
{
    long num = 1789;

    stringstream stream;  
    
    // Add long to the stream
    stream<<num;  
    
    // Get string object from the stream
    string str = stream.str();  
    
    cout<<str<<endl;

    return 0;
}

Output:

1789

In the stringstream, we inserted a long, and the stream converted the long to string. Then, in the end, we requested a string object from the stream.

Convert long to string using boost::lexical_cast()

The C++ boost library provides a template function for data type conversion. It helps to convert elements from one data type to another. We can use that to convert a long to a string. For example,

#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

int main()
{
    long num = 3456;
    
    // Convert long to string using boost library
    string str = lexical_cast<string>(num);  
    
    cout<<str<<endl;

    return 0;
}

Output:

3456

Summary:

We learned about three different ways to convert a long to a string in C++.

Advertisements

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top