CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jul 2002
    Posts
    3

    simple string concatenation question

    if I have an integer (int i), and I want to append it to the end of a string expression, does this work:
    string str = "number_is_" + i;
    so that the desired value of str is
    number_is_1

  2. #2
    Join Date
    May 2001
    Posts
    472
    you have to convert the integer to a string first. Check out the atoi function.
    Ce n'est que pour vous dire ce que je vous dis.

  3. #3
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    atoi converts a string to an integer. I think what lisa188 wants is an integer to a string

    This method is not very efficient. It is just the C++ version of sprintf. It depends on which version of IO stream you are using. There is the pre-STL version and the STL version.

    If you are using the STL version,

    ostringstream catted;
    catted << "number_is_" << i;
    // the result is in catted.str (). This is a string

    If you are using the pre-STL version
    ostrstream catted;
    catted << "number_is_" << i;
    // the result is in catted.str (). This is a const char*.
    // once you access it, you are responsible for deleting it.
    Succinct is verbose for terse

  4. #4
    Join Date
    Jun 2002
    Posts
    1,417
    Here are two more possiblities:

    char buf[16];
    sprintf(buf,"%d", i);
    string str = "number_is_" + buf;

    or

    char buf[32];
    sprintf(buf,"number_is_%d", i);
    string str = buf;

  5. #5
    Join Date
    Jul 2002
    Posts
    3

    Thank you

    great; these things all work. Thanks!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured