Search code examples
c++c++11character-encodingiomanip

cout << setw doesn't align correctly with åäö


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;
}

This produces the following output:

COL_A  COL_B  COL_C
ABC    ÅÄÖ ABC

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

COL_A  COL_B  COL_C
ABC    ABC    ABC  

Why is this happening?


Solution

  • 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;
    }
    

    Demo