Thread: String Library & Appending Integer :: C++

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348

    String Library & Appending Integer :: C++

    Hi.

    I am stuck with an intesting problem with the string library. Let say declare a string (empty). To start out, I append a statement. Afterward, I want to append an integer and end it with a char. For example:

    string strTemp;

    for (int i = 0; i < 5; ++i)
    {
    strTemp += "Count down: ";
    strTemp += i; // Problem!
    strTemp += '...";
    cout << strTemp.c_str() << endl;
    }

    The output of the code above will looking something like:

    Cout download: *character that 0 represents*
    Cout download: *character that 1 represents*
    Cout download: *character that 2 represents*
    Cout download: *character that 3 represents*
    Cout download: *character that 4 represents*

    The output I want is:

    Cout download: 0
    Cout download: 1
    Cout download: 2
    Cout download: 3
    Cout download: 4

    Is there a way to append or concatenate an integer into a string variable and have the string variable store the integer as an integer instead of the ACSII character the integer represents?

    Thanks,
    Kuphryn

    P.S. I experience the same problem with STL container. Furthermore, the problem remains even if I switch from a string to a vector<int>. It seems the two do not mix.

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    4
    Well, a string is a container of characters, so you're not going to be able to store an int as an actual int in a string. One way to deal with this is to convert the int into a string first, and then append it.

    There's also a little trick you can use, if you're sure that your integer is only one digit, you can convert it to the corresponding char by adding the ascii value of '0' to it.

    i.e.

    mystring += i + '0'; // Only works if i is one digit


    Owlet

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Thanks everyone.

    BlackClaw from Ars Technica mentioned ostringstream. It works great.

    Kuphryn

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  2. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM