【发布时间】:2016-03-06 19:57:25
【问题描述】:
我需要输出一些可能是 UTF-8 多字节的数据,并且我需要使用setw() 对其进行格式化。
当字符为多字节序列时,对齐丢失,setw() 无法正常工作。
//#include <stdio.h>
#include <locale>
#include <iostream>
//#include <fstream>
#include <iomanip>
//#include <sstream>
int main(int argc, char **argv)
{
std::locale l=std::locale("en_US.utf8");
std::locale::global(l);
std::cout.imbue(l);
std::cout<<std::endl;
std::cout<<std::setw(40)<<std::right<<"hi “my” friend"<<std::endl;
std::cout<<std::setw(40)<<std::right<<"hi -my- friend"<<std::endl;
return 0;
}
输出是:
hi “my” friend
hi -my- friend
我错过了什么?
我必须指出,“ 和” 这两个字符不是普通的",而是另外两个字符,在 UTF-8 中每个字符由三个字节表示。
【问题讨论】:
-
遗憾的是,注入 UTF-8 语言环境不会使格式化函数识别 UTF-8。完成任务的最简单方法是将所有内容都转换为 wchar_t 并使用宽字符流。
标签: c++ utf-8 locale cout setw