I thought this would be really simple but it\'s presenting some difficulties. If I have
std::string name = \"John\";
int age = 21;
How do I
#include <sstream> std::ostringstream s; s << "John " << age; std::string query(s.str());
std::string query("John " + std::to_string(age));
#include <boost/lexical_cast.hpp> std::string query("John " + boost::lexical_cast<std::string>(age));
In C++11, you can use std::to_string
, e.g.:
auto result = name + std::to_string( age );
As a one liner: name += std::to_string(age);
If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age)
.
Another way is to use stringstreams:
std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;
A third approach would be to use sprintf
or snprintf
from the C library.
char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;
Other posters suggested using itoa
. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.
This problem can be done in many ways. I will show it in two ways:
Convert the number to string using to_string(i)
.
Using string streams.
Code:
#include <string>
#include <sstream>
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
string name = "John";
int age = 21;
string answer1 = "";
// Method 1). string s1 = to_string(age).
string s1=to_string(age); // Know the integer get converted into string
// where as we know that concatenation can easily be done using '+' in C++
answer1 = name + s1;
cout << answer1 << endl;
// Method 2). Using string streams
ostringstream s2;
s2 << age;
string s3 = s2.str(); // The str() function will convert a number into a string
string answer2 = ""; // For concatenation of strings.
answer2 = name + s3;
cout << answer2 << endl;
return 0;
}
There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format
#include <boost/format.hpp>
#include <string>
int main()
{
using boost::format;
int age = 22;
std::string str_age = str(format("age is %1%") % age);
}
and Karma from Boost.Spirit (v2)
#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
using namespace boost::spirit;
int age = 22;
std::string str_age("age is ");
std::back_insert_iterator<std::string> sink(str_age);
karma::generate(sink, int_, age);
return 0;
}
Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.