c-plus-plus
  1. c-plus-plus-c-int-to-string

C++ int to string

In C++, it is often necessary to convert an integer (int) to a string (std::string) for various purposes. This can be achieved using various methods and libraries available in C++.

Syntax

#include <string>
// Method 1: General method using std::to_string
int x = 10;
std::string str = std::to_string(x);

// Method 2: C++11 method using std::to_string
int y = 20;
std::string str2 = std::to_string(y);

// Method 3: Using stringstream
int z = 30;
std::stringstream ss;
ss << z;
std::string str3 = ss.str();

Example

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

int main() {
    int x = 10;
    std::string str = std::to_string(x);
    std::cout << "The string is: " << str << std::endl;

    int y = 20;
    std::string str2 = std::to_string(y);
    std::cout << "The string is: " << str2 << std::endl;

    int z = 30;
    std::stringstream ss;
    ss << z;
    std::string str3 = ss.str();
    std::cout << "The string is: " << str3 << std::endl;

    return 0;
}

Output

The string is: 10
The string is: 20
The string is: 30

Explanation

In the above example, we have three different methods to convert an integer to a string.

  • In the first method, we have used std::to_string which is a general method in C++ to convert an integer to a string.
  • In the second method, we have used std::to_string which is a C++11 method to convert an integer to a string.
  • In the third method, we have used stringstream to convert an integer to a string.

Use

Converting an integer to a string can be helpful in many scenarios. For example, when you need to print an integer along with a string or when you need to concatenate an integer to a string.

Important Points

  • Conversion from integer to string can be done using std::to_string or stringstream.
  • std::to_string is a general method and std::to_string is a C++11 method for this conversion.
  • std::to_string and stringstream gives the same result.
  • Using stringstream, you can also perform other conversions like float to string, double to string, etc.

Summary

In summary, conversion from integer to string is a common requirement in C++ programming. You can achieve this conversion using std::to_string or stringstream. Both give the same result and can be used interchangeably. These methods are helpful in various cases where you need to print or concatenate an integer with string in C++.

Published on: