2013-03-01 45 views
2

我想连接一个std::stringWCHAR*,结果应该是WCHAR*C++ /串连的std :: string和WCHAR *至* 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 *'

+7

这很好。你尝试过什么吗? – Rapptz 2013-03-01 05:10:44

+0

你不受欢迎。尝试一下,向我们展示一些努力或使用示例,然后编辑您的问题。 :3c – 2013-03-01 05:12:27

+1

yes ma..ha..aster(* squeeking sound *)... maste ... ma .. ma .. – 2013-03-01 05:12:42

回答

4

如果您致电string.c_str()以获取原始缓冲区,它将返回一个常量指针以指示您不应该尝试更改缓冲区。当然,你不应该试图连接任何东西。使用第二个字符串类实例,并让运行时为您完成大部分工作。

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”将是无效的。

+0

对于'std :: wstring(L“程序”)+1; //或输出+ = L“程序”;'(我不确定'operator +'是否返回std :: wstring',因为它是非成员函数,不同于'operator + ='。) – n611x007 2013-05-07 15:39:58

0

作为文档说

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

你不能通过你的常量wchar1作为目标,因为该函数将更改这个,然后返回。所以你最好

  • 分配适当大小的WCHAR阵列
  • 您的字符串复制到它与您的纽利分配WCHAR阵列作为目标
  • 呼叫wcsncat。

但是,我不知道你是否不能仅仅使用字符串来完成你的操作,这更像是C++的方式。 (阵列是C风格)