将宽CString转换为char*

Convert wide CString to char*

本文关键字:char 转换 CString 将宽      更新时间:2023-10-16

这个问题已经被问过很多次了,也有很多答案——没有一个适合我,似乎还有很多人。问题是关于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时,坚持使用CStringwchar_t

如果你需要将数据上传到网页或其他地方,那么使用CW2ACA2W进行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);