Convert char* to wchar_t*

I've been at this one for a while now, and have tried a few solutions. I am trying to convert a char string to a wide char string.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    if (argc > 1)
        {
        wchar_t* arg1 = (wchar_t*) argv[1];
        cout << arg1 << endl;
        return 0;
    }
    else return 1;
}


Apart from the above, here are the solutions that I have tried:
http://www.cplusplus.com/reference/clibrary/cstdlib/mbstowcs/
1
2
wchar arg1[512];
mbtowcs(arg1, argv[1], 512);

http://msdn.microsoft.com/en-us/library/bb202786.aspx
1
2
3
4
#include <windows.h>
...
wchar_t arg1[512];
MultiByteToWideChar(CP_ACP, MB_COMPOSITE, argv[1], 512, arg1, 0);

and:
wchar_t* arg1 = argv[1];

I have also seen some suggest using "wcout" instead of cout:
wcout << arg1 << endl;

but "wcout" isn't found:
: error: `wcout' was not declared in this scope
Last edited on
Your compiler is not compliant if it does not declare [code]std::wcout[/b].
That said, it won't do what you think it will...

The wcout stream simply calls narrow() on every character you give it, and prints the result. The default implementation is stupid.
http://www.cplusplus.com/reference/iostream/ios/narrow/

The other options are:

To install a proper locale -- unfortunately locales in C++ are broken (because they aren't properly standardized).

To write your own codecvt facet (most difficult, actually).

To write your own wide stream output stream (simplest option, actually). If you decide to go with this option, you'll need to know how to manipulate the Win32 console. Start by reading through here:
http://www.google.com/search?btnI=1&q=msdn+WriteConsoleOutputCharacter
The Win32 Console functions can work with 16-bit characters. Keep in mind that you must set the proper Code Page first. Alas.


Oh, finally, to get the wide character command line in Windows, use the GetCommandLineW() function.
http://www.google.com/search?btnI=1&q=msdn+GetCommandLine
Also useful with this is the CommandLineToArgvW() function
http://www.google.com/search?btnI=1&q=msdn+CommandLineToArgvW

Good luck!
Thanks, I won't worry about it for now, as long as it is being converted to wide char. My goal isn't actually to print it out, but because it wasn't printing I didn't think it was being converted.
Topic archived. No new replies allowed.