Thread: std::string construction

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    630

    std::string construction

    Hello

    Whats the shortest/easiest way to do the following thing with std::string:


    Code:
    std::string r;
    r = somestr + "@" + somestr2;
    Is it possible to do this in one line statement?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
       std::string r(somestr + "@" + somestr2);
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    I believe that will only work if the left-most string in the + concatenation sequence is a std::string (or has an equivalent operator+() ).

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Yes, if somestr is some other type such as a char[], you'd have to use something like
    Code:
    std::string r(std::string(somestr) + "@" + somestr2);
    That would be the shortest way, but perhaps not the easiest. This might be easier:
    Code:
    std::string r = somestr;
    r += "@";
    r += somestr2;
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 13
    Last Post: 12-14-2007, 03:34 PM
  2. Improving my code
    By rwmarsh in forum C++ Programming
    Replies: 14
    Last Post: 07-08-2006, 11:18 AM
  3. Debugging help
    By cuddlez.ini in forum C++ Programming
    Replies: 3
    Last Post: 10-24-2004, 07:08 PM
  4. DLL and std::string woes!
    By Magos in forum C++ Programming
    Replies: 7
    Last Post: 09-08-2004, 12:34 PM
  5. returning std::string
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 09-24-2001, 08:31 PM