how to format a two or one digits number in a two char string?

Ok, maybe this is a very stupid question but wich is the cleanest way to convert an int to a System::String with always at least 2 chars...

Now, I do this:
String* convertTo2CharString(int num){
if(num<10)
  return String::Concat(S"0", Convert::ToString(int));
else
  return Convert::ToString(int);
}

I suppose that with the String::Format, I can do it with one line of code but I don't know how. Tnx.



Answer this question

how to format a two or one digits number in a two char string?

  • jhobitz

    Oops, I edited my second post while you were answering...
    couldn't find solution yet.


  • mattpdk

    Here's a good place to start for information on all the new stuff that's coming in Visual C++ 2005.

    http://msdn.microsoft.com/visualc/whidbey/



  • neetu_fzr

    How about this:

    using namespace System;

    int main()
    {
       int i = 5;
       Console::WriteLine(i.ToString()->Format("02"));
    }


  • s_karthik_au

    Ok, now it works, tnx very much...
    But I feel dumb now... A new syntax Is this related to .net 2.0 platform and Whidbey Maybe I'm doing code that is already deprecated... :( Info, info, info, please.... a link would be great, start searching... Ok, after this I'll stop to stress you...


  • Deepak Juneja

    In Managed C++ int is a synonym for System::Int32 which is a value type and hence has the property that it can inherit from System::Object (and System::ValueType) when this is required.

  • Rick Bunnell

    Wow...
    I didn't know that I could dereference integers... I'm a little bit confused now; so an int in Managed C++ is derived from Object and it's allocated in the managed stack (and is a managed type)

    But, it doesn't compile... :(
    error C2661: 'System::String::Format' : no overloaded function takes 1 arguments
    I'm now looking in MSDN library to find answer...


  • pinkpanter

    I aplogize: I missed the fact that you weren't using the new syntax. Try this variation:

    #using <mscorlib.dll>

    using namespace System;

    int main()
    {
        int i = 5;

        Console::WriteLine(i.ToString("d2"));
    }



  • how to format a two or one digits number in a two char string?