How to concatenate a std::string and an int in C++?

C++Server Side ProgrammingProgramming

In this program we will see how to concatenate a string and integer type data in C++. To concatenate string and integer data, we have to convert integer to string at first. To convert it we are using stringstream. This provides some features. It takes number or string then make it string.

Input: String “str” and Number 10
Output: Concatenated string “str10”

Algorithm

Step 1: Take string and number
Step 2: Convert number to string
Step 3: Concatenate them
Step 4: End

Example Code

 Live Demo

#include <iostream>
#include <sstream>
using namespace std;
string int_to_str(int x) {
   stringstream ss;
   ss << x;
   return ss.str();
}
int main() {
   string my_str = "This is a string: ";
   int x = 50;
   string concat_str;
   concat_str = my_str + int_to_str(x);
   cout << concat_str;
}

Output

This is a string: 50
raja
Published on 28-Mar-2019 08:49:28
Advertisements