Todd
Todd

Reputation:

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.

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.

Upvotes: 3

Views: 2907

Answers (2)

Larry Osterman
Larry Osterman

Reputation: 16142

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 :(

Upvotes: 1

Assaf Lavie
Assaf Lavie

Reputation: 76093

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.

Upvotes: 3

Related Questions