Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I concatenate a string and wstring?

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;
like image 514
Ben Avatar asked Sep 02 '25 02:09

Ben


1 Answers

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;
like image 159
emlai Avatar answered Sep 04 '25 14:09

emlai