0

I need to print unicode symbols to the file, but I get their codes instead.

Here is an example:

#include <iostream> #include <fstream> using namespace std; int main () { int code = 33; wchar_t sym = wchar_t(code); ofstream output ("output.txt"); output << sym << "\n"; output.close(); return 0; } 

So I expect to see ! in my file, but I see 33. How can I fix it?

3
  • 4
    Shouldn't you be using wofstream ? cplusplus.com/reference/fstream/wofstream Commented Sep 10, 2019 at 23:40
  • Yes, use std::wofstream instead. And FYI, cplusplus.com is generally considered to be a poor C++ reference site, you should use cppreference.com (wofstream) Commented Sep 10, 2019 at 23:53
  • Do you want UTF-8 or UTF-16? And do you want BOM at the start of the file. And does your viewer open the file in the proper format? Commented Sep 11, 2019 at 0:57

2 Answers 2

1

How can I print unicode characters to text file

I expect to see ! in my file

Here is an example writing

UTF-8:

std::ofstream output("output.txt"); output << u8"!\n"; 

UTF-16:

std::basic_ofstream<char16_t> output ("output.txt"); output << u"!\n"; 

UTF-32:

std::basic_ofstream<char32_t> output ("output.txt"); output << U"!\n"; 

wchar_t may also work, but only when the wide compilation character encoding is unicode. Whether it is UTF-16 or UTF-32 or something else depends on the system:

std::wofstream output ("output.txt"); output << L"!\n"; 
Sign up to request clarification or add additional context in comments.

Comments

0

std::ofstream operates on char data and does not have any operator<< that takes wchar_t data as input. It does have operator<< that takes int, and wchar_t is implicitly convertible to int. That is why you are getting the character outputted as a number.

You need to use std::wofstream instead for wchar_t data.

1 Comment

@igor_bal how the wchar_t data is encoded depends on the locale that is imbue()'d into the stream

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.