# Error c4244 wchar to char

This topic is 2360 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have this for a wchar to char conversion and get the c4244 error? Not sure how to get around it

 inline std::string WStringToString(const std::wstring& s) { std::string temp(s.length(), ' '); std::copy(s.begin(), s.end(), std::back_inserter(temp)); return temp; } 

Thanks!

##### Share on other sites
Hi this may be a bit verbose, but i found it years ago on this site. Can't find where it was but I have a copy here.

 string ConvertWideToString(const wstring &wideString) { vector<char> asciiCharacters(wideString.length()); const wchar_t *nextWideCharacter; char *nextAsciiCharacter; mbstate_t state; int res = use_facet< codecvt<wchar_t, char, mbstate_t> >(locale("C")).out( state, wideString.c_str(), &wideString.c_str()[wideString.length()], nextWideCharacter, &asciiCharacters[0], &asciiCharacters[0] + wideString.length(), nextAsciiCharacter ); if(res == codecvt_base::error) throw runtime_error("Wide to ASCII conversion failed"); return string(&asciiCharacters[0], nextAsciiCharacter - &asciiCharacters[0]); } 

It works from the times I've used it. Hope it helps...

##### Share on other sites
Thanks that got rid of the warning... From the looks of it, this is cross platform ok?

THanks!

##### Share on other sites
Oh the localisation crimes that original code tried to commit! Good thing it gave a warning.

If you're working with Visual Studio, and use a little ATL, then there's a handly little one-liner you can use to do the conversion. The _bstr_t class can both accept and be cast to char* and wchar_t*, making it handy for conversion either direction.

##### Share on other sites
Thanks that got rid of the warning... From the looks of it, this is cross platform ok?THanks!

No problem mate... By the way, just to answer, yes It is multi-platform as it is written with pure C++ STL.
You can easily compile with both Windows and Linux as I have.I have moved away from wchar_t, as there are inconsistencies with the size of the data type (Windows it is 2 bytes and on other OS it is 4 bytes, if my memory is correct).
So in the latest C++standards, it is recommended to use a new data type char32_t, as it is same size on all platforms. The information on char32_t is scarce, but out there. The first place to look is CPP Reference Link to char32_t. You can also use char16_t as that is also new in the C++ standards. It may not be fully implemented on all compilers, so research on it before going into it 100% on any projects.