Search code examples
printfwidestringc++builder-2010

how to correctly format WideString using sprintf or wprintf


I am using this code to format WideString but with no success! It prints unexpecting results :(

here is my code

WideString s;
dep=new TStringList();
while(!DM->tDepPln->Eof)
    {
    //where tDepPlnFltNo is mysql field type of WideString
        s.sprintf(L"%-11S",DM->tDepPlnFltNo->AsWideString);
        dep->Add(s);
        DM->tDepPln->Next();
    }

when I use s.sprintf(L"%-11S","blablabla"); it works but when i set to mysql field type of WideString it's not!! I think the problem is with conversion!

How to correct it ???


Solution

  • Your format specifier is using uppercase S, which tells Unicode flavors of ...printf() functions (such as the one used inside of WideString:::sprintf()) to expect a char* instead of a wchar_t* (and Ansi flavors of ...printf() functions to expect a wchar_t* instead of a char*). That is why s.sprintf(L"%-11S","blablabla") works - you are passing it a char*.

    For what you are attempting, you need to use lowercase s instead. You also need to use the WideString::c_bstr() method when passing a WideString value to a ...printf() function, eg:

    s.sprintf(L"%-11s", DM->tDepPlnFltNo->AsWideString.c_bstr());