将std::string和wchar*连接到wchar*

visual C++ / Concatenate std::string and wchar* to wchar*

本文关键字:wchar 连接 std string      更新时间:2023-10-16

我想连接一个std::stringWCHAR*,结果应该在WCHAR*

我尝试了以下代码

size_t needed = ::mbstowcs(NULL,&input[0],input.length());
std::wstring output;
output.resize(needed);
::mbstowcs(&output[0],&input[0],input.length());
const wchar_t wchar1 = output.c_str();
const wchar_t * ptr=wcsncat( wchar1, L" program", 3 );

我得到了以下错误

错误C2220:警告被视为错误-没有'object'文件生成

错误C2664: 'wcsncat':无法将参数1从'const wchar_t*'转换为'wchar_t*'

如果您调用string.c_str()来获取原始缓冲区,它将返回一个const指针,表明您不应该尝试更改缓冲区。当然你不应该尝试连接任何东西到它上面。使用第二个字符串类实例,让运行库为您完成大部分工作。

std::string input; // initialized elsewhere
std::wstring output;
output = std::wstring(input.begin(), input.end());
output = output + std::wstring(L" program"); // or output += L" program";
const wchar_t *ptr = output.c_str();

还要记住这一点。一旦"output"超出作用域并销毁,"ptr"将无效。

如文档所述

wchar_t * wcsncat (wchar_t * destination, wchar_t * source, size_t num);将源的第一个num宽字符附加到目标,加上一个终止的空宽字符。返回目的地。(来源:http://www.cplusplus.com/reference/cwchar/wcsncat/)

不能传递const wchar1作为目标,因为函数会修改它并返回它。所以你最好

  • 分配一个合适大小的wchar数组
  • 复制你的字符串到它
  • 使用新分配的wchar数组作为目标调用wcsncat。

然而,我想知道你是否不能仅仅使用字符串来完成你的操作,这更像是c++的方式。(数组是c风格的)