Thread: Adding integers to a string

  1. #1
    Registered User
    Join Date
    Feb 2002
    Posts
    145

    Adding integers to a string

    How can I add an integer value to the end of a string? Is there a way to convert the integer to a string and then add it on?

    Example:
    Code:
    // using free Borland C++ Compiler v5.5
    // using default string.h library
    
    string Base = "Default";
    int Number = 5;
    
    Base = (Base + Number);
    Thanks for any help.
    "Um...well..."
    -Kyoto Oshiro

  2. #2
    Registered User
    Join Date
    Jan 2004
    Posts
    33
    Try using a stringstream.
    “Focused, hard work is the real key to success. Keep your eyes on the goal, and just keep taking the next step towards completing it. " -John Carmack

  3. #3
    Hardware Engineer
    Join Date
    Sep 2001
    Posts
    1,398

    Talking I'll probably get flamed for using C...

    But in C you use sprintf()

    Code:
    #include <iostream.h>
    #include <stdio.h>
    
    int main()
    {
         char Base[20] = "Default";
         int Number = 5;
         sprintf(Base, "%s %d", Base, Number);
         cout << Base;
    return 0;
    }

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Stringstreams is the answer:
    Code:
    #include <string>
    #include <sstream>
    
    int Age = 89;
    std::string Name("Jack");
    
    std::stringstream SS;
    std::string S;
    
    SS << "Hi, my name is " << Name << " and I'm " << Age << " years old!";
    S = SS.str();
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  4. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  5. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM