convert integer to string

How to convert integer to string in C++?

In this tutorial, we will learn about how to convert integer to string in C++. Data type conversion is a fundamental process used extensively in programming. There are various situations where you must change a variable’s data type. You can achieve this conversion in two primary ways: through Implicit type conversion. It is handled by the compiler, or through Explicit type conversion, performed manually. Most programming languages offer built-in methods for explicit type conversion.

convert integer to string

Converting data from an integer to a string format enables you to easily manipulate the data using string operations. String operations often prove more convenient than arithmetic operations in certain scenarios. For instance, consider this example for displaying the current date.

Different Approaches to convert integer to string in C++

  • By using the String Stream Class
  • By using the std::to_string

1. By using the String Stream Class

Converting an integer to a string in C++ is a common task, and one way to achieve this is by using the std::stringstream class. The std::stringstream class allows you to manipulate strings as if they were streams, making it easy to convert different data types to strings and vice versa.

#include <iostream>
#include <sstream>

int main() {
    int number = 42; // Integer you want to convert to a string
    
    std::stringstream ss; // Create a stringstream object
    ss << number; // Insert the integer into the stringstream
    
    std::string str_number = ss.str(); // Convert stringstream to string
    
    std::cout << "Integer as a string: " << str_number << std::endl;
    
    return 0;
}


Output :

Integer as a string: 42

In this program, we create a std::stringstream object ss, insert the integer number into it using the << operator, and then convert the string stream to a string with ss.str(). Finally, we print the integer as a string to the console.

2. By Using the std::to_string

In C++, converting an integer to a string is a common task, especially when dealing with input/output operations or constructing strings. One simple and convenient way to perform this conversion is by using std::to_string.

#include <iostream>
#include <string>

int main() {
    int number = 42; // Replace 42 with your integer value
    std::string str_number = std::to_string(number);

    std::cout << "Integer as a string: " << str_number << std::endl;

    return 0;
}


Output :

Integer as a string: 42

In this program, we declare an integer variable number and initialize it with the value 42. We then use std::to_string to convert this integer to a string and store the result in the str_number variable. Finally, we print the integer as a string to the console, which will display “Integer as a string: 42”. You can replace 42 with any integer value, you want to convert to a string.