Skip to main content
GameDev.net gamedev.net
🔒 Locked

concatenating a c++ string

Started by moucard May 18, 2004 at 9:27 AM 6 replies 850+ views
Original Post
moucard
moucard
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?
moucard
moucard
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)
Red Ant
Red Ant
Couldn''t you overload operator + for Strings and ints, doubles, etc, returning a reference to a String?
Miserable
Miserable

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]
rypyr
rypyr
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 ]
moucard
moucard
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!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.