我需要输出一些可能是 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 中是每三个字节表示。
最佳答案
字符串文字 "hi -my- friend"
包含 14 个字符。字符串文字 "hi “my” friend"
包含 18 个字符:symbols “
and ”
are encoded by 3 characters/bytes . cout
原样输出这些字符,它是将3字节序列转换为单个符号的目标终端。
因此,从流的角度来看,一切正常:它输出 (width - strlen(literal) )
填充字符,然后是 strlen(literal)
字符,宽度
总计。它不处理可能的多字节序列,也不知道目标终端将多个字符转换为一个符号。
关于c++ - setw() 在包含 UTF-8 多字节字符/代码点的字符串上注入(inject)错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35831798/