4

I have a wstring variable and a string variable in C++. I want to concatenate them both, but simply adding them together produces a build error. How can I combine them both? If I need to convert the wstring variable to a string, how would I accomplish this?

//A WCHAR array is created by obtaining the directory of a folder - This is part of my C++ project
WCHAR path[MAX_PATH + 1] = { 0 };
GetModuleFileNameW(NULL, path, MAX_PATH);
PathCchRemoveFileSpec(path, MAX_PATH);

//The resulting array is converted to a wstring
std::wstring wStr(path);

//An ordinary string is created
std::string str = "Test";

//The variables are put into this equation for concatenation - It produces a build error
std::string result = wStr + str;
Ben
  • 1,299
  • 3
  • 17
  • 37
  • Following the Windows conventions the `std::string` is not able to represent the wide string, in general. If it is meant to be used as a filesystem path then that's *one* particular conversion, but if it's meant to be displayed to the user then that's *a different* conversion. So it depends very much on what you intend to use the `std::string` for, what's its **purpose**? – Cheers and hth. - Alf Dec 06 '15 at 01:20
  • "ordinary string" is a strange term. Which character set and encoding do you want the result to be? If it's not a Unicode encoding (for example, UTF-8), you'll loose data because `GetModuleFileNameW` is going to be a counted sequence of UTF-16 code units. – Tom Blodget Dec 06 '15 at 05:01

1 Answers1

7

Convert the wstring to a string first, like this:

std::string result = std::string(wStr.begin(), wStr.end()) + str;

or if wStr contains non-ASCII characters:

std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::string wStrAsStr = converter.to_bytes(wStr);
std::string result = wStrAsStr + str;
Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • This conversion loses information in the general case, and depending on the conventions used it may produce an invalid `std::string` value (e.g. invalid bytes for UTF-8 encoding), and so recommending it without mentioning the limitations is a bit reckless. – Cheers and hth. - Alf Dec 06 '15 at 01:21
  • 1
    Added a safer alternative. – Emil Laine Dec 06 '15 at 01:31
  • 1
    :) Now it doesn't lose information, which is good, but since this is Windows programming it's no longer very useful: doesn't work as a path, and doesn't present properly in GUI stuff (I believe the streams can be configured to present it properly in a console, but not sure about that). It can however be used as e.g. serialization of the wide string. It all depends on the **purpose**, which the OP neglects to mention. – Cheers and hth. - Alf Dec 06 '15 at 01:40