【问题标题】:setw and accentuated characterssetw 和重音字符
【发布时间】:2021-12-02 02:34:02
【问题描述】:

我想在 C++ 上显示一个“漂亮”的国家列表及其 ISO 货币代码。 问题是我的数据是法语的,并且有强调的字符。这意味着阿尔及利亚实际上写成“Algérie”,而瑞典变成了“Suède”。

map<string, string> currencies; /* ISO code for currency and country name: CAD/Canada */ 
for (auto &cursor: countries)
  cout << setw(15) << left << cursor.second << right << " - " cursor.first << endl;

如果地图包含阿尔及利亚、加拿大和瑞典,结果如下所示:

Canada          - CAD
Algérie        - DZD
Suède          - SEK

你看到阿尔及利亚和瑞典不“漂亮”吗?这是因为即使“Algérie”有 7 个可见字符,而“Suède”有 5 个,但对于 setw,它们“算作”多了一个。 “Algérie”中的“é”和“Suède”中的“蔓算”为两个字符,因为它们是“特殊重音字符”。

是否有一种优雅简单的方法来确保 DZD 和 SEK 自动与 CAD 对齐?

【问题讨论】:

    标签: c++ setw


    【解决方案1】:
    1. 转换为使用std::wstring 而不是std::string
    2. 转换为使用宽字符串常量(L"stuff""stuff"
    3. 转换为使用std::wcout 而不是std::cout
    4. 使用setlocale 设置UTF-8 语言环境
    5. 使用 wcout.imbue 为 UTF-8 语言环境配置 wcout

    例子:

    #include <map>
    #include <string>
    #include <iostream>
    #include <iomanip>
    #include <locale>
    
    int main() {
        setlocale(LC_ALL, "en_US.utf8");
        std::locale loc("en_US.UTF-8");
        std::wcout.imbue(loc); 
        std::map<std::wstring, std::wstring> dict 
            { {L"Canada",L"CAD"}, {L"Algérie",L"DZD"}, {L"Suède",L"SEK"} };
        for (const auto& [key, value]: dict) {
            std::wcout << std::setw(10) << key << L" = " << value << std::endl;
        }
    }   
    

    【讨论】:

    • 谢谢你,迈克!
    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2023-03-03
    • 2019-09-08
    相关资源
    最近更新 更多