0

Is there a way to make a string grab a set text and a variable? Something like this:

std::string morning = "morning"; std::string str = "Good " [insert morning here] ", user!"; 

Obviously I'm trying to do something a bit more complex than the example I just gave, but I believe you can kinda understand what I'm trying to do.

Thanks in advance, guys!

2
  • do you want to concatenate strings? Or string with numbers too? Commented Feb 10, 2015 at 17:19
  • Which C++ book are you using? String concatenation is fairly basic. Commented Feb 14, 2015 at 17:48

3 Answers 3

2

You simply use std::string::operator+, something like:

std::string str = "Good " + morning + ", user!"; 
Sign up to request clarification or add additional context in comments.

Comments

1

Another method is to use std::ostringstream:

std::string morning = "morning"; unsigned int user_id = 384; std::ostringstream out_stream; out_stream << "Good " << morning << ", user #" << user_id; std::string str = out_stream.str(); 

Comments

0

Unfortunately neither ostream nor the operator+ worked. I ended using some char and push_back stuff. Anyway, thanks guys!

Comments