Related
See the example to understand
int rnd = rand() %10;
string Folder = "c://foldername";
string final_name = Folder + rnd; // here the target
/* I want the result like that (random folder name)
foldername5
foldername10
foldername3
foldername20
foldername17
*/
Use std::stringstream as:
#include <sstream> //include this
std::stringstream ss;
ss << Folder << rnd;
string final_name = ss.str();
Or you can write this just in one line:
string final_name = stringbuilder() << Folder << rnd;
All that it needs a small utility class:
struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
Using this class, you can create std::string on the fly as:
void f(const std::string & file ) {}
f(stringbuilder() << Folder << rnd);
std::string s = stringbuilder() << 25 << " is greater than " << 5 ;
In c++ you use stringstream to convert integers to strings.
int rnd = rand() %10;
string Folder = "c://foldername";
stringstream ss;
ss << Folder << rnd;
string final_name = ss.str(); // here the target
In C++ the best way to do this is to use a stringstream:
#include<sstream>
...
std::stringstream stream;
stream << "c://foldername" << rand() %10;
stream.str(); // now contains both path and number
Say this:
std::string final_name = Folder + std::to_string(rnd);
If you have an old compiler that doesn't support C++11, you can use boost::lexical_cast, or std::snprintf, or string streams.
Convert rnd (it is in integer type) to string type then do the same
string final_name = Folder + rnd;
I have to concatenate char with int.
Here's my code:
int count = 100;
char* name = NULL;
sprintf((char *)name, "test_%d", count);
printf("%s\n", name);
Nothing printed. What's the problem?
You didn't allocate any memory into which sprintf could copy its result. You might try:
int count = 100;
char name[20];
sprintf(name, "test_%d", count);
printf("%s\n", name);
Or even:
int count = 100;
char *name = malloc(20);
sprintf(name, "test_%d", count);
printf("%s\n", name);
Of course, if your only goal is the print the combined string, you can just do this:
printf("test_%d\n", 100);
If you programm C++ use sstream instead:
stringstream oss;
string str;
int count =100
oss << count;
str=oss.str();
cout << str;
You have to allocate memory for name first. In C, library functions like sprintf won't make it for you.
In fact, I am very surprised that you didn't get a segmentation fault.
A simple workaround would be using char name[5+11+1] for the case of 32-bit int.
I use boost::format for this.
#include <boost/format.hpp>
int count = 100;
std::string name = boost::str( boost::format("test_%1%") % count );
Since the answer is tagged C++, this is probably how you should do it there:
The C++11 way: std::string str = "Hello " + std::to_string(5);
The Boost way: std::string str = "Hello " + boost::lexical_cast<std::string>(5);
#include <iostream>
#include <string>
#include <sstream>
int count = 100;
std::stringstream ss;
ss << "Helloworld";
ss << " ";
ss << count ;
ss << std::endl;
std::string str = ss.str();
std::cout << str;
const char * mystring = str.c_str();
How can I convert a double into a const char, and then convert it back into a double?
I'm wanting to convert the double to a string, to write it to a file via fputs, and then when I read the file, it will need to be converted back into a double.
I'm using Visual C++ 2010 Express Edition.
If you just want to write the double values to file, you can simply write it, without converting them into const char*. Converting them into const char* is overkill.
Just use std::ofstream as:
std::ofstream file("output.txt")'
double d = 1.989089;
file << d ; // d goes to the file!
file.close(); //done!
Since you added C++ to your tags, I suggest you use std::stringstream:
#include <sstream>
stringstream ss;
ss << myDouble;
const char* str = ss.str().c_str();
ss >> myOtherDouble;
You can use these functions to convert to and from:
template <class T>
bool convertFromStr(string &str, T *var) {
istringstream ss(str);
return (ss >> *var);
}
template <class T>
string convertToStr(T *var) {
ostringstream ss;
ss << *var;
return ss.str();
}
Example:
double d = 1.234567;
string str = convertToStr<double>(&d);
cout << str << endl;
double d2;
convertFromStr<double>(str, &d2);
cout << d2 << endl;
Use this funcition :
const char* ConvertDoubleToString(double value){
std::stringstream ss ;
ss << value;
const char* str = ss.str().c_str();
return str;
}
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 combine them to get a single string "John21"?
In alphabetical order:
std::string name = "John";
int age = 21;
std::string result;
// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);
// 2. with C++11
result = name + std::to_string(age);
// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);
// 4. with FastFormat.Write
fastformat::write(result, name, age);
// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);
// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();
// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);
// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);
// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);
// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);
is safe, but slow; requires Boost (header-only); most/all platforms
is safe, requires C++11 (to_string() is already included in #include <string>)
is safe, and fast; requires FastFormat, which must be compiled; most/all platforms
(ditto)
is safe, and fast; requires the {fmt} library, which can either be compiled or used in a header-only mode; most/all platforms
safe, slow, and verbose; requires #include <sstream> (from standard C++)
is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms
is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms
is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms
safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only
is safe, but slow; requires Poco C++ ; most/all platforms
In C++11, you can use std::to_string, e.g.:
auto result = 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.
#include <iostream>
#include <sstream>
std::ostringstream o;
o << name << age;
std::cout << o.str();
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}
Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.
This is the easiest way:
string s = name + std::to_string(age);
If you have C++11, you can use std::to_string.
Example:
std::string name = "John";
int age = 21;
name += std::to_string(age);
std::cout << name;
Output:
John21
It seems to me that the simplest answer is to use the sprintf function:
sprintf(outString,"%s%d",name,age);
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
Then your usage would look something like this
std::string szName = "John";
int numAge = 23;
szName += to_string<int>(numAge);
cout << szName << endl;
Googled [and tested :p ]
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;
}
In C++20 you'll be able to do:
auto result = std::format("{}{}", name, age);
In the meantime you can use the {fmt} library, std::format is based on:
auto result = fmt::format("{}{}", name, age);
Disclaimer: I'm the author of the {fmt} library and C++20 std::format.
If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:
template <typename L, typename R> std::string operator+(L left, R right) {
std::ostringstream os;
os << left << right;
return os.str();
}
Then you can write your concatenations in a straightforward way:
std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);
std::cout << bar << std::endl;
Output:
the answer is 42
This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.
If you are using MFC, you can use a CString
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
Managed C++ also has a
string formatter.
As a one liner: name += std::to_string(age);
The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:
#include <sstream>
#define MAKE_STRING(tokens) /****************/ \
static_cast<std::ostringstream&>( \
std::ostringstream().flush() << tokens \
).str() \
/**/
Now you can format strings like this:
int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}
As a Qt-related question was closed in favour of this one, here's how to do it using Qt:
QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);
The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.
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.
std::ostringstream
#include <sstream>
std::ostringstream s;
s << "John " << age;
std::string query(s.str());
std::to_string (C++11)
std::string query("John " + std::to_string(age));
boost::lexical_cast
#include <boost/lexical_cast.hpp>
std::string query("John " + boost::lexical_cast<std::string>(age));
Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.
#include <iostream>
#include <locale>
#include <string>
template <class Facet>
struct erasable_facet : Facet
{
erasable_facet() : Facet(1) { }
~erasable_facet() { }
};
void append_int(std::string& s, int n)
{
erasable_facet<std::num_put<char,
std::back_insert_iterator<std::string>>> facet;
std::ios str(nullptr);
facet.put(std::back_inserter(s), str,
str.fill(), static_cast<unsigned long>(n));
}
int main()
{
std::string str = "ID: ";
int id = 123;
append_int(str, id);
std::cout << str; // ID: 123
}
Common Answer: itoa()
This is bad. itoa is non-standard, as pointed out here.
You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.
string name = "John";
int age = 5;
char temp = 5 + '0';
name = name + temp;
cout << name << endl;
Output: John5
There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:
char intToChar(int num)
{
if (num < 10 && num >= 0)
{
return num + 48;
//48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
}
else
{
return '*';
}
}
string intToString(int num)
{
int digits = 0, process, single;
string numString;
process = num;
// The following process the number of digits in num
while (process != 0)
{
single = process % 10; // 'single' now holds the rightmost portion of the int
process = (process - single)/10;
// Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10
// The above combination eliminates the rightmost portion of the int
digits ++;
}
process = num;
// Fill the numString with '*' times digits
for (int i = 0; i < digits; i++)
{
numString += '*';
}
for (int i = digits-1; i >= 0; i--)
{
single = process % 10;
numString[i] = intToChar ( single);
process = (process - single) / 10;
}
return numString;
}
In C++ 20 you can have a variadic lambda that does concatenate arbitrary streamable types to a string in a few lines:
auto make_string=[os=std::ostringstream{}](auto&& ...p) mutable
{
(os << ... << std::forward<decltype(p)>(p) );
return std::move(os).str();
};
int main() {
std::cout << make_string("Hello world: ",4,2, " is ", 42.0);
}
see https://godbolt.org/z/dEe9h75eb
using move(os).str() guarantees that the ostringstream object's stringbuffer is empty next time the lambda is called.
You can use the C function itoa() like this:
char buf[3];
itoa(age, buf, 10);
name += buf;
C# has a syntax feature where you can concatenate many data types together on 1 line.
string s = new String();
s += "Hello world, " + myInt + niceToSeeYouString;
s += someChar1 + interestingDecimal + someChar2;
What would be the equivalent in C++? As far as I can see, you'd have to do it all on separate lines as it doesn't support multiple strings/variables with the + operator. This is OK, but doesn't look as neat.
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.
#include <sstream>
#include <string>
std::stringstream ss;
ss << "Hello, world, " << myInt << niceToSeeYouString;
std::string s = ss.str();
Take a look at this Guru Of The Week article from Herb Sutter: The String Formatters of Manor Farm
In 5 years nobody has mentioned .append?
#include <string>
std::string s;
s.append("Hello world, ");
s.append("nice to see you, ");
s.append("or not.");
s += "Hello world, " + "nice to see you, " + "or not.";
Those character array literals are not C++ std::strings - you need to convert them:
s += string("Hello world, ") + string("nice to see you, ") + string("or not.");
To convert ints (or any other streamable type) you can use a boost lexical_cast or provide your own function:
template <typename T>
string Str( const T & t ) {
ostringstream os;
os << t;
return os.str();
}
You can now say things like:
string s = string("The meaning is ") + Str( 42 );
Your code can be written as1,
s = "Hello world," "nice to see you," "or not."
...but I doubt that's what you're looking for. In your case, you are probably looking for streams:
std::stringstream ss;
ss << "Hello world, " << 42 << "nice to see you.";
std::string s = ss.str();
1 "can be written as" : This only works for string literals. The concatenation is done by the compiler.
Using C++14 user defined literals and std::to_string the code becomes easier.
using namespace std::literals::string_literals;
std::string str;
str += "Hello World, "s + "nice to see you, "s + "or not"s;
str += "Hello World, "s + std::to_string(my_int) + other_string;
Note that concatenating string literals can be done at compile time. Just remove the +.
str += "Hello World, " "nice to see you, " "or not";
In C++20 you'll be able to do:
auto s = std::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Until then you could do the same with the {fmt} library:
auto s = fmt::format("{}{}{}", "Hello world, ", myInt, niceToSeeYouString);
Disclaimer: I'm the author of {fmt}.
To offer a solution that is more one-line-ish: A function concat can be implemented to reduce the "classic" stringstream based solution to a single statement.
It is based on variadic templates and perfect forwarding.
Usage:
std::string s = concat(someObject, " Hello, ", 42, " I concatenate", anyStreamableType);
Implementation:
void addToStream(std::ostringstream&)
{
}
template<typename T, typename... Args>
void addToStream(std::ostringstream& a_stream, T&& a_value, Args&&... a_args)
{
a_stream << std::forward<T>(a_value);
addToStream(a_stream, std::forward<Args>(a_args)...);
}
template<typename... Args>
std::string concat(Args&&... a_args)
{
std::ostringstream s;
addToStream(s, std::forward<Args>(a_args)...);
return s.str();
}
boost::format
or std::stringstream
std::stringstream msg;
msg << "Hello world, " << myInt << niceToSeeYouString;
msg.str(); // returns std::string object
auto s = string("one").append("two").append("three")
The actual problem was that concatenating string literals with + fails in C++:
string s;
s += "Hello world, " + "nice to see you, " + "or not.";
The above code produces an error.
In C++ (also in C), you concatenate string literals by just placing them right next to each other:
string s0 = "Hello world, " "nice to see you, " "or not.";
string s1 = "Hello world, " /*same*/ "nice to see you, " /*result*/ "or not.";
string s2 =
"Hello world, " /*line breaks in source code as well as*/
"nice to see you, " /*comments don't matter*/
"or not.";
This makes sense, if you generate code in macros:
#define TRACE(arg) cout << #arg ":" << (arg) << endl;
...a simple macro that can be used like this
int a = 5;
TRACE(a)
a += 7;
TRACE(a)
TRACE(a+7)
TRACE(17*11)
(live demo ...)
or, if you insist in using the + for string literals (as already suggested by underscore_d):
string s = string("Hello world, ")+"nice to see you, "+"or not.";
Another solution combines a string and a const char* for each concatenation step
string s;
s += "Hello world, "
s += "nice to see you, "
s += "or not.";
You would have to define operator+() for every data type you would want to concenate to the string, yet since operator<< is defined for most types, you should use std::stringstream.
Damn, beat by 50 seconds...
If you write out the +=, it looks almost the same as C#
string s("Some initial data. "); int i = 5;
s = s + "Hello world, " + "nice to see you, " + to_string(i) + "\n";
As others said, the main problem with the OP code is that the operator + does not concatenate const char *; it works with std::string, though.
Here's another solution that uses C++11 lambdas and for_each and allows to provide a separator to separate the strings:
#include <vector>
#include <algorithm>
#include <iterator>
#include <sstream>
string join(const string& separator,
const vector<string>& strings)
{
if (strings.empty())
return "";
if (strings.size() == 1)
return strings[0];
stringstream ss;
ss << strings[0];
auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
for_each(begin(strings) + 1, end(strings), aggregate);
return ss.str();
}
Usage:
std::vector<std::string> strings { "a", "b", "c" };
std::string joinedStrings = join(", ", strings);
It seems to scale well (linearly), at least after a quick test on my computer; here's a quick test I've written:
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <chrono>
using namespace std;
string join(const string& separator,
const vector<string>& strings)
{
if (strings.empty())
return "";
if (strings.size() == 1)
return strings[0];
stringstream ss;
ss << strings[0];
auto aggregate = [&ss, &separator](const string& s) { ss << separator << s; };
for_each(begin(strings) + 1, end(strings), aggregate);
return ss.str();
}
int main()
{
const int reps = 1000;
const string sep = ", ";
auto generator = [](){return "abcde";};
vector<string> strings10(10);
generate(begin(strings10), end(strings10), generator);
vector<string> strings100(100);
generate(begin(strings100), end(strings100), generator);
vector<string> strings1000(1000);
generate(begin(strings1000), end(strings1000), generator);
vector<string> strings10000(10000);
generate(begin(strings10000), end(strings10000), generator);
auto t1 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings10);
}
auto t2 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings100);
}
auto t3 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings1000);
}
auto t4 = chrono::system_clock::now();
for(int i = 0; i<reps; ++i)
{
join(sep, strings10000);
}
auto t5 = chrono::system_clock::now();
auto d1 = chrono::duration_cast<chrono::milliseconds>(t2 - t1);
auto d2 = chrono::duration_cast<chrono::milliseconds>(t3 - t2);
auto d3 = chrono::duration_cast<chrono::milliseconds>(t4 - t3);
auto d4 = chrono::duration_cast<chrono::milliseconds>(t5 - t4);
cout << "join(10) : " << d1.count() << endl;
cout << "join(100) : " << d2.count() << endl;
cout << "join(1000) : " << d3.count() << endl;
cout << "join(10000): " << d4.count() << endl;
}
Results (milliseconds):
join(10) : 2
join(100) : 10
join(1000) : 91
join(10000): 898
Here's the one-liner solution:
#include <iostream>
#include <string>
int main() {
std::string s = std::string("Hi") + " there" + " friends";
std::cout << s << std::endl;
std::string r = std::string("Magic number: ") + std::to_string(13) + "!";
std::cout << r << std::endl;
return 0;
}
Although it's a tiny bit ugly, I think it's about as clean as you cat get in C++.
We are casting the first argument to a std::string and then using the (left to right) evaluation order of operator+ to ensure that its left operand is always a std::string. In this manner, we concatenate the std::string on the left with the const char * operand on the right and return another std::string, cascading the effect.
Note: there are a few options for the right operand, including const char *, std::string, and char.
It's up to you to decide whether the magic number is 13 or 6227020800.
Maybe you like my "Streamer" solution to really do it in one line:
#include <iostream>
#include <sstream>
using namespace std;
class Streamer // class for one line string generation
{
public:
Streamer& clear() // clear content
{
ss.str(""); // set to empty string
ss.clear(); // clear error flags
return *this;
}
template <typename T>
friend Streamer& operator<<(Streamer& streamer,T str); // add to streamer
string str() // get current string
{ return ss.str();}
private:
stringstream ss;
};
template <typename T>
Streamer& operator<<(Streamer& streamer,T str)
{ streamer.ss<<str;return streamer;}
Streamer streamer; // make this a global variable
class MyTestClass // just a test class
{
public:
MyTestClass() : data(0.12345){}
friend ostream& operator<<(ostream& os,const MyTestClass& myClass);
private:
double data;
};
ostream& operator<<(ostream& os,const MyTestClass& myClass) // print test class
{ return os<<myClass.data;}
int main()
{
int i=0;
string s1=(streamer.clear()<<"foo"<<"bar"<<"test").str(); // test strings
string s2=(streamer.clear()<<"i:"<<i++<<" "<<i++<<" "<<i++<<" "<<0.666).str(); // test numbers
string s3=(streamer.clear()<<"test class:"<<MyTestClass()).str(); // test with test class
cout<<"s1: '"<<s1<<"'"<<endl;
cout<<"s2: '"<<s2<<"'"<<endl;
cout<<"s3: '"<<s3<<"'"<<endl;
}
You may use this header for this regard: https://github.com/theypsilon/concat
using namespace concat;
assert(concat(1,2,3,4,5) == "12345");
Under the hood you will be using a std::ostringstream.
If you are willing to use c++11 you can utilize user-defined string literals and define two function templates that overload the plus operator for a std::string object and any other object. The only pitfall is not to overload the plus operators of std::string, otherwise the compiler doesn't know which operator to use. You can do this by using the template std::enable_if from type_traits. After that strings behave just like in Java or C#. See my example implementation for details.
Main code
#include <iostream>
#include "c_sharp_strings.hpp"
using namespace std;
int main()
{
int i = 0;
float f = 0.4;
double d = 1.3e-2;
string s;
s += "Hello world, "_ + "nice to see you. "_ + i
+ " "_ + 47 + " "_ + f + ',' + d;
cout << s << endl;
return 0;
}
File c_sharp_strings.hpp
Include this header file in all all places where you want to have these strings.
#ifndef C_SHARP_STRING_H_INCLUDED
#define C_SHARP_STRING_H_INCLUDED
#include <type_traits>
#include <string>
inline std::string operator "" _(const char a[], long unsigned int i)
{
return std::string(a);
}
template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
!std::is_same<char, T>::value &&
!std::is_same<const char*, T>::value, std::string>::type
operator+ (std::string s, T i)
{
return s + std::to_string(i);
}
template<typename T> inline
typename std::enable_if<!std::is_same<std::string, T>::value &&
!std::is_same<char, T>::value &&
!std::is_same<const char*, T>::value, std::string>::type
operator+ (T i, std::string s)
{
return std::to_string(i) + s;
}
#endif // C_SHARP_STRING_H_INCLUDED
Something like this works for me
namespace detail {
void concat_impl(std::ostream&) { /* do nothing */ }
template<typename T, typename ...Args>
void concat_impl(std::ostream& os, const T& t, Args&&... args)
{
os << t;
concat_impl(os, std::forward<Args>(args)...);
}
} /* namespace detail */
template<typename ...Args>
std::string concat(Args&&... args)
{
std::ostringstream os;
detail::concat_impl(os, std::forward<Args>(args)...);
return os.str();
}
// ...
std::string s{"Hello World, "};
s = concat(s, myInt, niceToSeeYouString, myChar, myFoo);
Based on above solutions I made a class var_string for my project to make life easy. Examples:
var_string x("abc %d %s", 123, "def");
std::string y = (std::string)x;
const char *z = x.c_str();
The class itself:
#include <stdlib.h>
#include <stdarg.h>
class var_string
{
public:
var_string(const char *cmd, ...)
{
va_list args;
va_start(args, cmd);
vsnprintf(buffer, sizeof(buffer) - 1, cmd, args);
}
~var_string() {}
operator std::string()
{
return std::string(buffer);
}
operator char*()
{
return buffer;
}
const char *c_str()
{
return buffer;
}
int system()
{
return ::system(buffer);
}
private:
char buffer[4096];
};
Still wondering if there will be something better in C++ ?
In c11:
void printMessage(std::string&& message) {
std::cout << message << std::endl;
return message;
}
this allow you to create function call like this:
printMessage("message number : " + std::to_string(id));
will print : message number : 10
you can also "extend" the string class and choose the operator you prefer ( <<, &, |, etc ...)
Here is the code using operator<< to show there is no conflict with streams
note: if you uncomment s1.reserve(30), there is only 3 new() operator requests (1 for s1, 1 for s2, 1 for reserve ; you can't reserve at constructor time unfortunately); without reserve, s1 has to request more memory as it grows, so it depends on your compiler implementation grow factor (mine seems to be 1.5, 5 new() calls in this example)
namespace perso {
class string:public std::string {
public:
string(): std::string(){}
template<typename T>
string(const T v): std::string(v) {}
template<typename T>
string& operator<<(const T s){
*this+=s;
return *this;
}
};
}
using namespace std;
int main()
{
using string = perso::string;
string s1, s2="she";
//s1.reserve(30);
s1 << "no " << "sunshine when " << s2 << '\'' << 's' << " gone";
cout << "Aint't "<< s1 << " ..." << endl;
return 0;
}
Stringstream with a simple preproccessor macro using a lambda function seems nice:
#include <sstream>
#define make_string(args) []{std::stringstream ss; ss << args; return ss;}()
and then
auto str = make_string("hello" << " there" << 10 << '$');
This works for me:
#include <iostream>
using namespace std;
#define CONCAT2(a,b) string(a)+string(b)
#define CONCAT3(a,b,c) string(a)+string(b)+string(c)
#define CONCAT4(a,b,c,d) string(a)+string(b)+string(c)+string(d)
#define HOMEDIR "c:\\example"
int main()
{
const char* filename = "myfile";
string path = CONCAT4(HOMEDIR,"\\",filename,".txt");
cout << path;
return 0;
}
Output:
c:\example\myfile.txt
Have you tried to avoid the +=?
instead use var = var + ...
it worked for me.
#include <iostream.h> // for string
string myName = "";
int _age = 30;
myName = myName + "Vincent" + "Thorpe" + 30 + " " + 2019;