2

我想连接一个std::stringandWCHAR*并且结果应该在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:警告视为错误 - 未生成“对象”文件

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

4

2 回答 2

4

如果您调用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();

还要记住这一点。一旦“输出”超出范围并破坏,“ptr”将无效。

于 2013-03-01T05:32:42.227 回答
0

正如文件所说

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

您不能将 const wchar1 作为目标传递,因为该函数将修改它然后返回它。所以你最好

  • 分配适当大小的 wchar 数组
  • 将您的字符串复制到其中
  • 使用 newley 分配的 wchar 数组作为目标调用 wcsncat。

但是,我想知道您是否不能只使用字符串来进行操作,这更像是 C++ 的方式。(数组是 C 风格的)

于 2013-03-01T05:33:28.090 回答