[try Beta version]
Not logged in

 
How i can convert string to wchar_t ?

Nov 13, 2012 at 1:32am
I want to convert my string to whcar_t.

I try this code but i can't success :S

string username="UserName";

wstring widestr = wstring(username.begin(), username.end());

wchar_t* widecstr = widestr.c_str();
Last edited on Nov 13, 2012 at 1:32am
Nov 13, 2012 at 1:51am
There some narrow->wide conversion function somewhere but I can never remember where it is.

The easy/basic way to do it is just do a dumb copy:

1
2
3
4
5
6
string username = "whatever";
wstring wideusername;
for(int i = 0; i < username.length(); ++i)
  wideusername += wchar_t( username[i] );

const wchar_t* your_result = wideusername.c_str();


The better question, though, is why do you want to do this? If you are using wide strings... then use wide strings from the start. And if you aren't using wide strings, then why bother converting to them?
Nov 13, 2012 at 2:46am
It is actually a common need to cast between string types.

You can use std::copy() or you can use a wstring constructor:

1
2
3
4
5
6
7
wchar_t* wide_string = new wchar_t[ s.length() + 1 ];
std::copy( s.begin(), s.end(), wide_string );
wide_string[ s.length() ] = 0;

foo( wide_string );

delete [] wide_string;

1
2
3
wstring wide_string( s.begin(), s.end() );

foo( wide_string.c_str() );

This is just off the top of my head. I'm sure there are better ways to do it.
Nov 13, 2012 at 3:10am
1
2
3
4
5
6
7
8
9
10
11
#include <locale>
#include <string>
#include <iostream>

int main()
{
    std::wstring_convert< std::codecvt<wchar_t,char,std::mbstate_t> > conv ;
    std::string str = "Hello World!" ;
    std::wstring wstr = conv.from_bytes(str) ;
    std::wcout << wstr << L'\n' ;
}


Or if you are using GCC (which does not have std::wstring_convert), std::setlocale() followed by std::mbsrtowcs() http://en.cppreference.com/w/cpp/string/multibyte/mbsrtowcs
Nov 13, 2012 at 4:20am
If your C++ compiler supports C99 features, you can do one without the temporary std::wstring:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstring>
#include <iostream>
#include <string>
 
int main(void)
{
    std::string username = "username";
    const size_t len = username.length() + 1;
    wchar_t wcstring[len];

    swprintf(wcstring, len, L"%s", username.c_str());
    std::wcout << wcstring << std::endl;

    return (0);
}


Obviously, you can still do it without C99 feature support by allocating the wchar_t array on the heap. Your mileage will vary.
Last edited on Nov 13, 2012 at 4:26am
Topic archived. No new replies allowed.