0

I was trying to create a function that converts a string to a wstring, using the built-in function wsprintf.

For some reason, when I try to print the result wstring, nothing is printed, and when I try debugging, I saw it contains letters in Chinese (so I guess that the problem is that the sprintf function didn't add a leading zero-byte to each character for some reason, but I have no idea WHY).

Can someone please help me figure it out?

Here is what I did:

#include <iostream>
#include <string>

using std::wstring;
using std::string;
using std::wcout;
using std::endl;

wstring strToWstr(const string& str);

int main()
{
    string str = "test";
    wstring wstr = strToWstr(str);
    wcout << wstr << endl;
}

wstring strToWstr(const string& str)
{
    wchar_t* temp = NULL;

    temp = new wchar_t[str.length() + 1]; //allocated string with the right length

    swprintf(temp, str.length() + 1, L"%s", str.c_str());

    wstring res = temp;

    delete[] temp;
    return res;
}
aviad1
  • 354
  • 1
  • 10
  • Is there a reason you aren't just doing [this](https://stackoverflow.com/a/6691612/5494370) – Alan Birtles Apr 24 '20 at 13:04
  • `wprintf` clearly expects both the input and the output [to be wide](https://en.cppreference.com/w/cpp/io/c/fwprintf). – Zuodian Hu Apr 24 '20 at 13:15
  • @ZuodianHu for the buffers and format string yes but the `%s` specifier expects a narrow string, `%ls` would be for a wide string – Alan Birtles Apr 24 '20 at 13:33
  • @AlanBirtles I come from the background of C, so I didn't know you can do it like that... But I would still like to figure out why my solution doesn't work – aviad1 Apr 24 '20 at 13:36
  • @ZuodianHu That would be if I used %ls, but if I use %s the function should parse it as a regular null-terminated string (and not a wide one) – aviad1 Apr 24 '20 at 13:36
  • Are you using visual studio? Looks like microsoft don't follow the standard: https://learn.microsoft.com/en-us/cpp/c-runtime-library/format-specification-syntax-printf-and-wprintf-functions?view=vs-2019 `%s` expects a wide string for swprintf – Alan Birtles Apr 24 '20 at 13:39
  • I stand corrected. – Zuodian Hu Apr 24 '20 at 17:33
  • @AlanBirtles Apparently you're right. Thanks for the help. – aviad1 Apr 24 '20 at 18:08

0 Answers0