Archived

This topic is now archived and is closed to further replies.

moucard

concatenating a c++ string

Recommended Posts

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?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
string filename = blabla + "\\" + string(day) + "/" + string(month) + "/" + "/" + string(year) + ".trc";

Does that work?

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
you could use printf with %d, or maybe the itoa() function.

Share this post


Link to post
Share on other sites
Couldn''t you overload operator + for Strings and ints, doubles, etc, returning a reference to a String?

Share this post


Link to post
Share on other sites

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]

Share this post


Link to post
Share on other sites
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 ]

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites