gpt4 book ai didi

c++ - 如何连接字符串和 wstring?

转载 作者:行者123 更新时间:2023-11-30 03:46:24 73 4
gpt4 key购买 nike

我在 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,如this :

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;

关于c++ - 如何连接字符串和 wstring?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112798/

73 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com