How to convert int to string in C++

There are three ways possible to convert an integer to string in c++

  • Using std::to_string function

The string function converts numerical int value to string. It takes integer value as argument and returns a string object containing the representation of numerical value as a sequence of characters.

#include <string>
#include <iostream>
using namespace std;

int main() {
    int num = 25;
    // convert using to_string function
    string str = to_string(num);
    cout << "Integer converted to string: " << str;
    return 0;
}
  • Using string streams

The input or the output string stream can be used to convert numerical int value to string. Here we create a variable of output string stream class and then use the insertion operator to insert the integer value to stream, then we use str member function to return a string object with a copy of the current contents of the stream.

#include <string>
#include <sstream>
#include <iostream>
using namespace std;

int main() {
    int num = 25;
    // create object of output stream class
    ostringstream oss;
    // insert value into stream
    oss << num;
    string str = oss.str();
    cout << "Integer converted to string: " << str;
    return 0;
}
  • Using boost::lexical_cast function

This again is similar to string conversion function, where lexical_cast function from boost/lexical_cast.hpp library is used to convert a numerical int value to string.

#include <string>
#include <boost/lexical_cast.hpp>
#include <iostream>
using namespace std;

int main() {
    int num = 25;
    // use boost lexical_cast to convert int to string
    string str = boost::lexical_cast<string>(num);
    cout << "Integer converted to string: " << str;
    return 0;
}

Note: There is also itoa() function in C to convert int to string, but this is not defined in ANSI-C and is not part of C++, yet supported by some compilers.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int num = 25;
    char strBuff[30];
    // C-style function to convert int to string
    itoa(num,strBuff,10);
    printf("Integer converted to string: %s", strBuff);
    return 0;
}   

Leave a Reply

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.