Wednesday, April 6, 2011

How do I concatenate multiple C++ strings on one line?

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.

From stackoverflow
  • s += "Hello world, " + "nice to see you, " + "or not.";
    

    Those character array literals are not C++ std::strings - you ned 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 = "The meaning is " + Str( 42 );
    
    Ferruccio : You only need to explicitly convert the first one: s += string("Hello world,") + "nice to see you, " + "or not.";
    anon : Yes, but I couldn't face explaining why!
    bb : boost::lexical_cast - nice and similar on your Str function:)
  • boost::format

    or std::stringstream

    std::strinstream msg;
    msg << "Hello world, " << myInt  << niceToSeeYouString;
    msg.str(); // returns std::string object
    
    Marcin : +1 for boost::format
  • #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

  • 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...

    Tyler McHenry : You can't actually define new operators on built-in types like char and int.
  • Your code can be written as,

    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();
    
    j_random_hacker : Your 1st example is worth mentioning, but please also mention that it works only for "concatenating" literal strings (the compiler performs the concatenation itself).

0 comments:

Post a Comment