简体   繁体   中英

Converting fractions (1/8, 3/8, 5/8, 7/8) to UTF-8 in C++

I have to display fractions using the symbols and I can't seem to be able to display these 4. using

char UCP_VULGAR_FRACTION_ONE_HALF_UTF8 = L'\u00BD';
char UCP_VULGAR_FRACTION_ONE_QUARTER_UTF8 = L'\u00BC';
char UCP_VULGAR_FRACTION_THREE_QUARTERS_UTF8 = L'\u00BE';

I can get 1/2, 1/4 and 3/4 to display just fine ( cout<< (char)UCP_VULGAR_FRACTION_ONE_HALF_UTF8 ), but doing the same for those fractions:

char UCP_VULGAR_FRACTION_ONE_EIGHTH_UTF8 = L'\u215B';
char UCP_VULGAR_FRACTION_THREE_EIGHTHS_UTF8 = L'\u215C';
char UCP_VULGAR_FRACTION_FIVE_EIGHTHS_UTF8 = L'\u215D';
char UCP_VULGAR_FRACTION_SEVEN_EIGHTHS_UTF8 = L'\u215E';

Gets me [ , \\ , ] and ^ . What am I doing wrong? I tried g_unichar_to_utf8 with no success...

For UTF-8 you need to store multibyte characters - characters contained in one or more bytes. Typically these are stored in a std::string :

std::string const UCP_VULGAR_FRACTION_ONE_EIGHTH_UTF8 = u8"\u215B";
std::string const UCP_VULGAR_FRACTION_THREE_EIGHTHS_UTF8 = u8"\u215C";
std::string const UCP_VULGAR_FRACTION_FIVE_EIGHTHS_UTF8 = u8"\u215D";
std::string const UCP_VULGAR_FRACTION_SEVEN_EIGHTHS_UTF8 = u8"\u215E";

Or possibly a null terminated char array :

char const* UCP_VULGAR_FRACTION_ONE_EIGHTH_UTF8 = "\u215B";
char const* UCP_VULGAR_FRACTION_THREE_EIGHTHS_UTF8 = "\u215C";
char const* UCP_VULGAR_FRACTION_FIVE_EIGHTHS_UTF8 = "\u215D";
char const* UCP_VULGAR_FRACTION_SEVEN_EIGHTHS_UTF8 = "\u215E";

Use wchar_t instead of char . Also be aware that you can't print wchar_t using std::cout , you need to use wide version of std::cout which is std::wcout . BTW, If you use wcout with cout together, the program will crash most probably. so you may want to store these unicode characters in normal UTF-8 std::string instead of wchar_t , and print them using std::cout

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM