1

I'm converting the formatted strings to a single wchar_t*. When I have a stream containing %s, vswprintf somehow doesn't form a expected wchar_t* out of that formatted string. This is happening only in Windows(VS 2008) but works well in Mac (XCode 3.2.6)

For example,

my formatting function:

void widePrint(const wchar_t* fmt, ...) { 
    va_list args;
    va_start(args, fmt);

    wchar_t buf[32*1024] = {0};

    vswprintf(buf,(32*1024 - 1),fmt, args);

    ...//Prints buf 
    ...
}

this doesn't work in Windows but works well in Mac

std::string normalStr = "test Str";

std::wstring wideStr = L"wide test Str";

widePrint("Normal One: %s and Wide One: %ls", normalStr .c_str(), wideStr .c_str());

but if I convert %s to %ls, I mean converting std::string to std::wstring certainly works in Windows also

std::string normalStr = "test Str";

std::wstring normalStrW(normalStr .begin(), normalStr .end());

std::wstring wideStr = L"wide test Str";

widePrint("Normal One: %ls and Wide One: %ls", normalStrW.c_str(), wideStr .c_str());

When I searched online, I can see this Query in Stack Overflow

But even that link doesn't have a solution . How to get rid of this situation where I convert all my std::strings to std::wstrings. Infact convertion is a costly operation .

EDITS: Found out that "%S" -> Capital S , certainly helps to print char* in vswprintf. This below code works.

widePrint("Normal One: %S", normalStr.c_str());

But unfortunately "%S" doesn't work properly in Mac.Is there any workaround for this?

Community
  • 1
  • 1
  • Note that your `memset` call will only set half (or a quarter) of the buffer. `memset` expects its size in _bytes_ but you declare the array as 32k `wchar_t` which is two or four bytes (depending on platform). I recommend you skip the `memset`, and clear the buffer in the declaration: `wchar_t buf[32 * 1024] = { 0 };` – Some programmer dude May 31 '13 at 07:24
  • Thanks @JoachimPileborg Will surely follow that. (Edited my code above)Can you please help me with my question on how to get rid of converting %s to %ls – Gokulakrishnan Gopalakrishnan May 31 '13 at 07:32
  • See e.g. [this reference](http://en.cppreference.com/w/cpp/io/c/fwprintf), it has a nice table of all formatting codes. And it states that form normal `char` strings it's _always_ `%s` and for `wchar_t` strings it's _always_ `%ls`, even for the wide-character functions. – Some programmer dude May 31 '13 at 07:35
  • @JoachimPileborg You mean this is the behavior in Windows that vswprintf will expect %ls not %s. Actually I was seeing Mac accepts %s in vswprintf and prints fine. Thats why I thought Windows would also accept %s in the API. anyhow thanks for the clarification – Gokulakrishnan Gopalakrishnan May 31 '13 at 08:08
  • It looks like we can print char* using "%S" . unfortuantely in Mac, it doesn't work – Gokulakrishnan Gopalakrishnan May 31 '13 at 12:00

0 Answers0