John
John

Reputation: 6668

How to setLocale when converting char* to wchar_t*?

I won't lie, I pinched this code from https://stackoverflow.com/a/8032109/866333:

std::wstring *GetWC(const char *c)
{
    const size_t cSize = strlen(c)+1;
    std::wstring wc( cSize, L'#' );
    mbstowcs( &wc[0], c, cSize );
    //wchar_t wc[cSize];
    //mbstowcs (wc, c, cSize);

    return wc;
}

I'm trying to determine what is meant by, eg:

Remember to set relevant locale in main.

E.g., setlocale( LC_ALL, "" ).

In my case I read in UTF-8 (initially was ISO 8859-1 but that was breaking stuff) from files and I believe all my literals are ISO 8859-1 since that is my locale and I have too many source files to convert easily in Windows. I am targetting Android. I was kind of hoping to maybe mix ISO 8859-1 and UTF-8! Must I convert to one?

Let me get this right, I need to setLocale to delegate conversion routines? Just as I have them down pat! I'm keen for efficiency but it seems like this is messing with possibly static global variables? This is bound to have side effects if the locale was initially radically different?

Without setLocale or mbstowcs would https://stackoverflow.com/a/4826290/866333

wchar_t  ws[100];
swprintf(ws, 100, L"%hs", "ansi string");

be possible still? I don't see %hs in my libc manual.

Could setLocale obviate converting my full 8-bit (ASCII/ISO-8859-1) to multibyte UTF-8 and hence save string manipulation?

Sorry to have so many questions.

Upvotes: 0

Views: 895

Answers (1)

Anton Savin
Anton Savin

Reputation: 41321

Without using setLocale you can do simply

swprintf(ws, 100, L"%s", "ansi string");

Live demo

Upvotes: 1

Related Questions