宽字符串:CString,字符串 [英] wide string: CString, string
本文介绍了宽字符串:CString,字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// unicode project
CString str;
string s;
...
str.Format(L"..%s", s.c_str());
这会工作吗?我不确定我的代码是否在这里错误,但是str是垃圾字符串.
预先感谢.
Will this work? I''m not sure if my codes are wrong here but str is a garbage string.
Thanks in advance.
推荐答案
不.但是,您可以使用%S
(大写S
)格式说明符,例如
Nope. However you may use the%S
(uppercaseS
) format specifier, e.g.
std::string s = "foo";
CString str;
str.Format(L"%S", s.c_str());
我相信CString的格式期望其字符串参数为"T-String"(如果使用非unicode和"wchar_t *",则为"char *",如果您在项目的设置中使用的是unicode).从您使用宽字符串作为格式字符串这一事实出发,您正在使用unicode进行构建(啊,您甚至在我最初没有注意到的注释中显示了这一点).我的猜测是您会产生垃圾,因为%s希望获取一个宽字符串作为参数,但是您要用ansii-string进行输入.您可以尝试将s
替换为std::wstinrg
而不是string
.
I believe CString''s Format expects its string parameters to be a "T-String" (which is "char*" if you use non-unicode and "wchar_t *" or somesuch if you are using unicode in the project''s settings). Concluding from the fact that you used a wide-string as the format string, you are building with unicode (ah, and you even show that in a comment which i didn''t notice at first). My guess is that you get garbage because %s expects to get a wide string as parameter but you are feeding it with an ansii-string. You could try makings
anstd::wstinrg
instead ofstring
.
如其他解决方案中所述,您正在传递带有格式说明符的char字符串,该说明符要求传递一个宽弦.要将单个字符字符串与宽格式字符串一起使用,请使用%hs"格式说明符:
As already noted in the other solutions, you are passing a char string with a format specifier that requires passing a wide string. To use single char strings with wide format strings, use the ''%hs'' format specifier:
CString str;
LPCSTR lpszAnsi = "single char string";
LPCWSTR lpszWide = L"Unicode string";
str.Format(_T("%hs %ls"), lpszAnsi, lpszUnicode);
无论Unicode项目设置如何,该示例始终可以使用.
This example will always work regardless of the Unicode project setting.
这篇关于宽字符串:CString,字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文