将宽CString转换为char*
Convert wide CString to char*
这个问题已经被问过很多次了,也有很多答案——没有一个适合我,似乎还有很多人。问题是关于MFC下的宽cstring和8位字符。我们都想要一个在所有情况下都有效的答案,而不是一个特定的实例。
void Dosomething(CString csFileName)
{
char cLocFileNamestr[1024];
char cIntFileNamestr[1024];
// Convert from whatever version of CString is supplied
// to an 8 bit char string
cIntFileNamestr = ConvertCStochar(csFileName);
sprintf_s(cLocFileNamestr, "%s_%s", cIntFileNamestr, "pling.txt" );
m_KFile = fopen(LocFileNamestr, "wt");
}
这是一个添加到现有的代码(由别人)调试。我不想改变函数签名,它在很多地方使用。我不能更改sprintf_s的签名,它是一个库函数
你漏掉了很多细节,或者忽略了它们。如果您正在使用定义的UNICODE进行构建(看起来确实如此),那么转换为MBCS的最简单方法如下:
CStringA strAIntFileNameStr = csFileName.GetString(); // uses default code page
CStringA是CString的8位/MBCS版本。
但是,如果您正在转换的unicode字符串包含不在默认代码页中的字符,则它将填充一些垃圾字符。
您可以使用_wfopen()
而不是fopen()
,它将打开一个具有unicode文件名的文件。要创建文件名,可以使用swprintf_s()
.
一个在所有情况下都有效的答案,而不是一个特定的实例…
没有这样的事。
将 "ABCD..."
从wchar_t*
转换为char*
很容易,但对于非拉丁语言则不这样做。
当你的项目是unicode时,坚持使用CString
和wchar_t
。
如果你需要将数据上传到网页或其他地方,那么使用CW2A
和CA2W
进行utf-8和utf-16转换。
CStringW unicode = L"Россия";
MessageBoxW(0,unicode,L"Russian",0);//should be okay
CStringA utf8 = CW2A(unicode, CP_UTF8);
::MessageBoxA(0,utf8,"format error",0);//WinApi doesn't get UTF-8
char buf[1024];
strcpy(buf, utf8);
::MessageBoxA(0,buf,"format error",0);//same problem
//send this buf to webpage or other utf-8 systems
//this should be compatible with notepad etc.
//text will appear correctly
ofstream f(L"c:\stuff\okay.txt");
f.write(buf, strlen(buf));
//convert utf8 back to utf16
unicode = CA2W(buf, CP_UTF8);
::MessageBoxW(0,unicode,L"okay",0);
相关文章:
- 将无符号char*转换为std::istream*C++
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将函数参数"const char*"转换为"std::string_view"是
- C ++如何在使用"tolower"时将char转换为int
- 有没有办法在C++的赋值中将"char**"转换为"double"?
- JavaCPP 错误:无法将参数"1"的"char*"转换为"Abc*
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 如何在虚幻引擎4中将char*转换为TCHAR?
- C++:将模板类型 char 转换为 std::string
- strcmp/char* 转换无法按预期工作
- C++中的SQLite char*转换
- 无法从 const char* 转换为 const char *&
- 在 C++ 中将 char 转换为 int,而无需符号位传播
- 如果必须包含西里尔字符,如何将 char* 转换为 std::string?
- 试图使用strCMP时的char转换错误
- 无法从'const char *'转换为'LPCTSTR'
- 将 std::vector<char> 转换为字符* 会导致字符缺陷
- 使用 static_cast 将 char 转换为 int c++
- 如何在 C++(MFC) 中将 char* 转换为 LPCTSTR
- 无法将const char转换为字符串构造字符串