• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1070
  • Last Modified:

How to convert std::wstring to std::string

I did not see how I can easily convert wstring in string.
I understand wstring is twice the lenght of string.

In my case all the character is alpha numeric and '.:;/\'
1 Solution
You could use 'wcstombs()' (http://www.cplusplus.com/reference/cstdlib/wcstombs/) for that purpose, e.g.

wstring wstr = L"The quick brown fox...";
string str;
size_t len = wstr.length() + 1;
char* buf = new char[len]; // allocate temp. buffer

wcstombs(buf,wstr.c_str(),len); // do the conversion

str = buf; // assign to 'std::string'

delete[] buf; // clean up

Open in new window

PS: You might have guessed that, there's 'mbstowcs()' for the other way round
tommym121Author Commented:
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now