如何连接字符串和wstring

How do I concatenate a string and wstring?

本文关键字:字符串 wstring 连接 何连接      更新时间:2023-10-16

我在C++中有一个wstring变量和一个字符串变量。我想将两者连接起来,但简单地将它们添加在一起会产生构建错误。我如何将两者结合起来?如果我需要将wstring变量转换为字符串,我将如何实现这一点?

//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;

首先将wstring转换为string,如下所示:

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

或者如果wStr包含非ASCII字符:

std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
std::string wStrAsStr = converter.to_bytes(wStr);
std::string result = wStrAsStr + str;