
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Concatenate std::string and int in C++
Concatenate a string and an integer means, convert both the string and integer to a single string. In this article we will discuss all the approches to concatenate a std:string and an integer type using C/C++ program. First of all, let's understand the problem statement.
We are given a standard c++ string and an integer. We have to output a single string by combining the given string and integer. For example:
// Input String and Integer "Value = " 25 // Output String "Value = 25"
Concatenate String and Int in C++
Here is the list of approaches to concatenate string and integer using c++ program, which we will be discussing in this article with stepwise explanation and complete example codes.
Using Stringstream to Concatenate String and Int
The stringstream is an object of string class defined in the <sstream> header file. It is used for reading from the stream strings. Now, let's see how to use stringstream to concatenate string and int.
Example
In the code below we defined a stringstream object and passed both string and integer to it. The resulting string will be combination of string and integer.
#include <iostream> #include <sstream> using namespace std; int main() { int num = 7; stringstream ss; ss << "Item#" << num; string result = ss.str(); cout << result; }
The output of the above code will be:
Item#7
Using to_string() to Concatenate String and Int
In this method, first we will convert integer type to string type using to_string function. Then, we can simply use the + operator to combine first string and second string. Let's see how to implement this method using an example
Example
In the code below, used to_string function to convert 5 to the string "5". Then we used + operator to add "Count: " string and "5".
#include <iostream> using namespace std; int main() { string s = "Count: "; int num = 5; s += to_string(num); cout << s; }
The output of the above code will be:
Count: 5