cout<< setw与åäö的对齐方式不正确 [英] cout << setw doesn't align correctly with åäö

查看:96
本文介绍了cout<< setw与åäö的对齐方式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码重现了我的问题:

The following code reproduces my problem:

#include <iostream>
#include <iomanip>
#include <string>

void p(std::string s, int w)
{
   std::cout << std::left << std::setw(w) << s;
}

int main(int argc, char const *argv[])
{
   p("COL_A", 7);
   p("COL_B", 7);
   p("COL_C", 5);
   std::cout << std::endl;
   p("ABC", 7);
   p("ÅÄÖ", 7);
   p("ABC", 5);
   std::cout << std::endl;
   return 0;
}

这将产生以下输出:

COL_A  COL_B  COL_C
ABC    ÅÄÖ ABC

如果我将代码中的ÅÄÖ更改为例如 ABC,那么它起作用了:

If i change "ÅÄÖ" in the code to e.g. "ABC", then it works:

COL_A  COL_B  COL_C
ABC    ABC    ABC  

为什么会这样?

推荐答案

std :: wcout 插入适当的语言环境,您可能还必须切换到宽字符串。例如:

Along with imbuing std::wcout with the proper locale, you probably have to switch to wide strings as well. For example:

void p(std::wstring s, int w)
{
   std::wcout << std::left << std::setw(w) << s;
}

int main(int argc, char const *argv[])
{
   setlocale(LC_ALL, "en_US.utf8");
   std::locale loc("en_US.UTF-8");
   std::wcout.imbue(loc);

   p(L"COL_A", 7);
   p(L"COL_B", 7);
   p(L"COL_C", 5);
   std::wcout << std::endl;
   p(L"ABC", 7);
   p(L"ÅÄÖ", 7);
   p(L"ABC", 5);
   std::wcout << std::endl;
   return 0;
}

演示

这篇关于cout&lt;&lt; setw与åäö的对齐方式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆