19

I want to output a text to a file via two pointers that I have declared:

wchar_t   *Col1="dsffsd", *Col2="sdfsf";

Here is what I have tried:

std::ofstream fout;
fout.open(NativeDatabasePathHist);
fout<<"testing";
fout<<" "<<Col1<<" "<<Col2;
fout.close();

And here is what I am getting:

testing 113 113

Why is it that when I print Col1 and Col2, I am getting numbers instead of strings?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Aan
  • 12,247
  • 36
  • 89
  • 150
  • 3
    That shouldn't output anything since those literals aren't wide. Anyway, you probably want `std::owfstream` if you are indeed using wide strings. – chris Oct 15 '12 at 04:45
  • 2
    Related question: http://stackoverflow.com/questions/2493785/how-i-can-print-the-wchar-t-values-to-console – jogojapan Oct 15 '12 at 05:07
  • @jogojapan Thanks jogojapan you helped me :) – Aan Oct 15 '12 at 05:23
  • Thanks chris your comment was helpful but you write `std::owfstream` instead of `std::wofstream` :) – Aan Oct 15 '12 at 05:26
  • •Try ```WideCharToMultiByte``` to convert your unicode text into binary. – Supergamer Oct 02 '22 at 14:47

2 Answers2

22

First, use std::wofstream instead of std::ofstream.

Also, use the L prefix on your text string to indicate that your text is wide character text:

wchar_t   *Col1=L"dsffsd"
DavidRR
  • 18,291
  • 25
  • 109
  • 191
Dmitriy
  • 5,357
  • 8
  • 45
  • 57
0

Since you have written it using wide characters (wchar_t), you need to look at the resulting file with something that understands wide characters.

wallyk
  • 56,922
  • 16
  • 83
  • 148
  • I have to get `Col1` & `Col2` as `wchar_t`. How I can convert it to char? – Aan Oct 15 '12 at 04:51
  • @Aan: well, since those strings don't have any characters actually requiring a wide representation, you could simply change the type to `char`. If this is an example using dummy data, but real data will have 16-bit code points, then use a library function like `wctomb()` ("wide character to multi-byte"). – wallyk Oct 15 '12 at 05:12
  • In this case I tried `fout<<" "<<(char*)Col1<<" "<<(char*)Col2;` but this output the first character pointed by Col1 & Col2 ?? – Aan Oct 15 '12 at 05:17
  • @Aan: sorry, I meant change the first line to `char *Col1="dsffsd", *Col2="sdfsf";` – wallyk Oct 15 '12 at 05:18