CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: string format

  1. #1
    Join Date
    Apr 2001
    Location
    CA , USA
    Posts
    83

    string format

    I have to create some strings in the way cout works independent of data types.Is there any way to write the output to some char buffer or CString in a way similar to cout.

    int n=25;
    float f=5.11;
    char r ='A';

    cout<<"my age is = " <<n << "my height is = "<< f << "my grade is = " <<r;





    So i have to create such a string and then use message box and show that. I dont know how to write such formatted strings to some buffer...

    Any help is appreciated.

    Thanks
    Shashi



  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: string format

    CString::Format allows sprintf type of formatting ...


    int n=25;
    float f=5.11;
    char r ='A';
    //
    CString str;
    str.Format("my age is = %d , my height is = %f , my grade is = %c",n,f,r);
    MessageBox(str);






  3. #3
    Join Date
    Apr 2001
    Location
    CA , USA
    Posts
    83

    Re: string format

    hi

    I use sprintf now. But for that i should know the data type, to put all that %d %f etc.. which is not known to me or will be known at runtime.

    thanks
    shashi


  4. #4
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: string format

    Use the standard STL stringstream...

    #include <string>
    #include <sstream>
    #include <iostream>

    using std::cout;
    using std::endl;
    using std::string;
    using std::stringstream;

    int main()
    {
    int iInt = 25;
    float fFloat = 5.11;
    char cChar = 'A';
    stringstream strsStream;

    strsStream << "My age is = " << iInt << ", my height is = " << fFloat << ", my grade is = " << cChar;

    // You can now use the stringstream itself
    cout << strsStream.str() << endl;

    // Or copy its content back to a string
    string strString = strsStream.str();
    cout << strString << endl;

    return 0;
    }




    Ciao, Andreas

    "Software is like sex, it's better when it's free." - Linus Torvalds

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