concatenating a c++ string

Started by
6 comments, last by moucard 19 years, 11 months ago
Hi to everyone. How can I concatenate a string in C++ mixing with some unsigned integers as well? What I want to do is:

string name = "blabla"
unsigned int month = 12;
unsigned int day = 18;
unsigned int year = 2004;

string filename = blabla + "\\" + day + "/" + month + "/" +
     "/" + year + ".trc";
 
Meaning that day is converted to a string? Is there a C++ way or should I do it with a sprintf call?
Advertisement
string filename = blabla + "\\" + string(day) + "/" + string(month) + "/" + "/" + string(year) + ".trc";

Does that work?
No, it gives an error of:

error C2440: ''type cast'' : cannot convert from ''unsigned short'' to ''class std::basic_string,class st
d::allocator >''
No constructor could take the source type, or constructor overload resolution was ambiguous

(using VC++ 6.0)
you could use printf with %d, or maybe the itoa() function.
Couldn''t you overload operator + for Strings and ints, doubles, etc, returning a reference to a String?
string name = "blabla";unsigned int month = 12;unsigned int day = 18;unsigned int year = 2004;stringstream ss; // Declared in <sstream>ss << blabla << "\\" << day << "/" << month << "/" << "/" << year << ".trc";string s = ss.str(); // Extract string 

Stringstreams can also be used to read from, just like any other input streams (cin, file streams ...).

[edited by - Miserable on May 18, 2004 10:47:30 AM]
gahh...
It''s not String (a Java-ism?) it''s std::string.

You can use:

int v;
stringstream ss;
ss << "Hello this is an int: " << v << ....

and then convert the string stream to a string.

You can use wsprintf to format a char*.

You can use itoa().

Regards,
Jeff

[ CodeDread ]
Yep, the stringstream thingy worked like a charm
I''ve never heard of them, thanks guys! Just when I was ready to use sprintf. It''s not that I don''t like C but I''m trying to learn C++ and stick with it, don''t mix code. Thank you all for your time!

This topic is closed to new replies.

Advertisement