Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 428
Yimin Rong Avatar asked Jun 10 '26 08:06

Yimin Rong


1 Answers

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 :-)

like image 173
TCS Avatar answered Jun 12 '26 22:06

TCS