简体   繁体   English

将C ++ LPCWSTR打印到文件

[英]Printing a C++ LPCWSTR to a file

I'm trying to print an LPCWSTR value to a file, but it only prints the address, not the value. 我正在尝试将LPCWSTR值打印到文件,但它只打印地址,而不是值。

I've tried dereferencing the variable (using *) to get the value , but this doesn't work either. 我已经尝试解除引用变量(使用*)来获取值,但这也不起作用。

How can I print the value ? 我该如何打印该值?

void dump(LPCWSTR text){

  ofstream myfile("C:\\myfile.txt", ios::app );
  myfile << text << endl;
  myfile.close();

}

Thanks in advance. 提前致谢。

Use wofstream (basic_ofstream). 使用wofstream (basic_ofstream)。 The reason this will work is because the w versions of the std streams are designed to work with wide character strings and data. 这将起作用的原因是因为std流的w版本被设计为使用宽字符串和数据。 The narrow version you are using will see a wide string which probably contains some embedded nulls and will think it is the end of the string. 您正在使用的窄版本将看到一个宽字符串,可能包含一些嵌入的空值,并认为它是字符串的结尾。

wofstream will generate an output that is also unicode (without a BOM). wofstream将生成一个也是unicode的输出(没有BOM)。 That may not be what Brian wants. 这可能不是Brian想要的。

Unfortunately if you want your file to be 8 bit characters, you're going to step out of C++ strings and convert the unicode strings into 8 bit characters. 不幸的是,如果你希望你的文件是8位字符,你将逐步退出C ++字符串并将unicode字符串转换为8位字符。

You can use wcstombs to convert the string to 8 bit characters. 您可以使用wcstombs将字符串转换为8位字符。 The conversion is done in the current locale, so make sure you use setlocale to ensure that your conversion happens in the correct locale. 转换是在当前语言环境中完成的,因此请确保使用setlocale确保转换以正确的语言环境进行。 Unfortunately the documentation for setlocale indicates that it won't work to convert to UTF-8 :( 不幸的是,setlocale的文档表明它无法转换为UTF-8 :(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM