C++ 如何将 Wchar_t* 转换为 const char*

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8098113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:59:39  来源:igfitidea点击:

How to convert Wchar_t* to const char*

c++wchar

提问by saroll

I am a kind of new for c++ , while working on the windows CE .net compact application

我是 c++ 的新手,同时在 windows CE .net 紧凑型应用程序上工作

while trying to write hexa datas to a file

尝试将 hexa 数据写入文件时

CString dataBlock1;
dataBlock1 = "";

CString temp;
for(int i = 0; i < rLen; i++)
{
temp.Format(L"%02X ",rec[i]);
dataBlock1 += temp;

}

std::ofstream out(file);

I am getting this error can not convert parameter 1 from wchar * to const char* on while using the below write function to write hexa datas to a file

我收到此错误无法将参数 1 从 wchar * 转换为 const char* on 同时使用以下写入函数将 hexa 数据写入文件

out.write(myReader.dataBlock1.GetBuffer(),myReader.dataBlock1.GetLength());

how can we convert wchar_* to const char* to make the write function work.

我们如何将 wchar_* 转换为 const char* 以使 write 函数工作。

Thanks.

谢谢。

采纳答案by az4dan

You can use the wcstombsfunction, reference here.

您可以使用该wcstombs功能,请参考此处

回答by Scott Conger

Windows has a set of classes and functions that take wchar_t, which is text stored as UTF-16, and char, which is text stored in your ANSI character set. If you have pointer to wchar_t you either need to use an appropriate class or function that accepts wchar_t, or you need to convert the data to your ANSI character set.

Windows 有一组类和函数,它们采用 wchar_t(以 UTF-16 格式存储的文本)和 char(以 ANSI 字符集存储的文本)。如果您有指向 wchar_t 的指针,您要么需要使用接受 wchar_t 的适当类或函数,要么需要将数据转换为您的 ANSI 字符集。

In this case, you want the wchar_t variant of ofstream, wofstream.

在这种情况下,您需要 ofstream wofstream 的 wchar_t 变体。