Thread: how do i do an int to CString conversion

  1. #1
    Unregistered
    Guest

    Question how do i do an int to CString conversion

    I have a question about strings, specifically CStrings in visual c++ MFC apps. I was wondering how to convert ints and other numbers so i can concatenate them with other CStrings. Is there any kind of function to do this?

  2. #2
    Registered User Azuth's Avatar
    Join Date
    Feb 2002
    Posts
    236
    If you want to concatenate an int with a string, you want your int to be a string.

    I beleive you're looking for...
    atoi for string to int, and its related functions for floats etc.
    Last edited by Azuth; 05-22-2002 at 01:26 AM.
    Demonographic rhinology is not the only possible outcome, but why take the chance

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    59

    Typecasting

    If you want a variable to act like another then you can use type casting. I believe it is explained in the tutorial on the cprogramming home page.

  4. #4
    Registered User
    Join Date
    May 2002
    Posts
    49
    convert everything to string...

    with MFC:
    Code:
    int my_int = 100;
    char my_char = '$';
    char* my_str = "I want ";
    CString str;
    str.Format("Do %s%c%d?", my_str, my_char, my_int);   // just like printf
    str is : "Do I want $100?"

    with STL:
    Code:
    int my_int = 100;
    char *my_char = '$';
    char my_str = "I want ";
    strstream ss;
    
    ss << "Do " << my_str << my_char << my_int << '?' << ends;
    string str(ss.c_str());
    str is : "Do I want $100?"

    with C style:
    please use sprintf.


    sorry, a bug ... I debug it. Edited.
    Last edited by Hotman_x; 05-22-2002 at 08:52 AM.
    Hello, everyone.

  5. #5
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    This is what I usally do
    Code:
    CString csTemp;
    int iEggs = 5;
    
    csTemp.Format("I want %d eggs",iEggs);
    MessageBox(csTemp);

  6. #6
    Registered User
    Join Date
    May 2002
    Posts
    49
    Supplement:

    convert everything to string with Boost Template Library(www.boost.org):
    Code:
    int my_int = 100;
    char my_char = '$';
    char *my_str = "I want ";
    string str = lexical_cast<string>my_str + lexical_cast<string>my_char + lexical_cast<string>my_int + "?";
    str is : "I want $100?"
    Hello, everyone.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory leak
    By aruna1 in forum C++ Programming
    Replies: 3
    Last Post: 08-17-2008, 10:28 PM
  2. Working with random like dice
    By SebastionV3 in forum C++ Programming
    Replies: 10
    Last Post: 05-26-2006, 09:16 PM
  3. Replies: 2
    Last Post: 03-24-2006, 08:36 PM
  4. Replies: 4
    Last Post: 11-23-2003, 07:15 AM
  5. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-02-2003, 12:26 AM