Yimin Rong
Yimin Rong

Reputation: 2027

C++: convert char * to wstring

Arguments in argv[] are UTF-8 encoded. I would like to do something like:

#include <wstring>
#include <???>

void doWhatever(wstring &ws);

using ???;

int main(int argc, char *argv[])
{
    while (--argc)
    {
        // Convert argv to wstring
        wstring ws = ???(argv[argc]);
        doWhatever(ws);
    }
    return EXIT_SUCCESS;
}

The ??? I don't know. I'm sure this is trivial for C++ people, but searching it just brings up a lot of noise.

Upvotes: 3

Views: 6553

Answers (2)

TCS
TCS

Reputation: 5890

That a very good question! :-)

  1. As Maxim wrote: mbstowcs()

  2. wsprintf() with "%S" (Capital "S"). In wsprintf() "S" means multi-byte string (in sprintf() "S" means wide-char).

  3. You can use std::wstring_convert and choose the UTF-8 encoding. I THINK its "codecvt_utf8_utf16"

For windows:

  1. MultiByteToWideChar() in WINAPI

  2. If you set to the clipboard using SetClipboardData() the ASCII text using CF_TEXT, windows allows you to GetClipboardData() for CF_UNICODETEXT doing the conversion for you!

You can also do it hardcore manually (and work only in some of the cases) by adding "NULLs" between 2 ASCII characters.

That's all comes to mind right now :-)

Upvotes: 1

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136208

On UNIX/Linux use iconv.

On Windows use mbstowcs.

There is also a standard C++ mbstowcs, but its interface is a bit lacking.

Upvotes: 0

Related Questions