tags:

views:

319

answers:

2

I'm trying to print an LPCWSTR value to a file, but it only prints the address, not the value.

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.

+1  A: 

Use 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. 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.

Assaf Lavie
The reason the "narrow" version does not work is because there is no operator<<(ostream, wchar_t*). There is operator<<(ostream, void*) though, and this is what gets selected in this case.
Éric Malenfant
+1  A: 

wofstream will generate an output that is also unicode (without a BOM). That may not be what Brian wants.

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.

You can use wcstombs to convert the string to 8 bit characters. The conversion is done in the current locale, so make sure you use setlocale to ensure that your conversion happens in the correct locale. Unfortunately the documentation for setlocale indicates that it won't work to convert to UTF-8 :(

Larry Osterman
Assuming that by "output" you mean "what gets written to the file": It is inaccurate to say that wofstream will generate Unicode output. What it outputs depends on the imbued locale (the codecvt facet, more precisely) of the filebuf.
Éric Malenfant
It is also inaccurate to say that an external conversion is needed to get "8 bit characters" to the file. wofstream *does* write bytes to the file, not wchar_ts: it's filebuf performs the wchar_t->char conversion using the locale's codecvt facet.
Éric Malenfant