igor_ball
igor_ball

Reputation: 188

C++: How can I print unicode characters to text file

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?

Upvotes: 0

Views: 697

Answers (2)

eerorika
eerorika

Reputation: 238491

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";

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 598449

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.

Upvotes: 0

Related Questions