Combining variables into one string

This is a discussion on Combining variables into one string within the C++ Programming forums, part of the General Programming Boards category; Hi, I'm having a pretty simple (I hope) problem, but I just can't figure it out. I need to combine ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    4

    Question Combining variables into one string

    Hi, I'm having a pretty simple (I hope) problem, but I just can't figure it out.

    I need to combine several variables into one string. For example if I have
    Code:
    string name = "Joe";
    int age = 55;
    
    string description;
    I want to arrange it so that description = "Joe: 55".

    The best solutions I could come up with are
    Code:
    description = name ": " age;
    and
    description = name + ": " + age;
    and neither of those work at all. What should I do?

  2. #2
    Registered User
    Join Date
    Jun 2006
    Posts
    5
    Use stringstreams.
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    int main()
    {
        string name = "Joe";
        int age = 55;
    
        ostringstream os;
        os << name << ": " << age;
        string description = os.str();
        
        cout << description << endl;
        
        return 0;
    }

  3. #3
    Registered User
    Join Date
    Oct 2007
    Posts
    4
    Okay, that works perfectly! Thanks very much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using SSCANF input string output two variables
    By kevndale79 in forum C Programming
    Replies: 9
    Last Post: 10-02-2006, 02:57 PM
  2. RicBot
    By John_ in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2006, 06:52 PM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. Another overloading "<<" problem
    By alphaoide in forum C++ Programming
    Replies: 18
    Last Post: 09-30-2003, 10:32 AM
  5. "Operator must be a member function..." (Error)
    By Magos in forum C++ Programming
    Replies: 16
    Last Post: 10-28-2002, 01:54 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21