7

My problem is shown in the following minimal example:

#include <iostream>
#include <string>
#include <iomanip>
int main()
{
    int width = 15;
    std::cout << std::left;
    std::cout << std::setw(width) << "Prints well" << std::setw(width) << "This too" << '\n';
    std::cout << std::setw(width) << "\u221E" << std::setw(width) << "This not?" << '\n';
    std::cout << std::setw(width+2) << "\u221E" << std::setw(width) << "This is good" << '\n';
}

Compiled using g++, it prints:

Prints well    This too       
∞            This not?      
∞              This is good

So it seems that the unicode symbol uses 3 spaces from the setw instead of one. Is there a simple way to fix this, not knowing beforehand whether a unicode character will be in the string?

YSC
  • 38,212
  • 9
  • 96
  • 149
user119879
  • 331
  • 1
  • 7
  • Hello and welcome on StackOverflow. Nice first question. – YSC Apr 16 '18 at 13:29
  • 2
    Possible duplicate of [cout << setw doesn't align correctly with åäö](https://stackoverflow.com/questions/29188948/cout-setw-doesnt-align-correctly-with-%c3%a5%c3%a4%c3%b6) – YSC Apr 16 '18 at 13:41
  • 1
    Although I [tested it with your specific case](http://coliru.stacked-crooked.com/a/f9602ef2a7f31f73) and did not get a satisfying result. – YSC Apr 16 '18 at 13:42
  • 1
    The `operator<<` will use the equivalent of `strlen(string)` to get a byte count and then pad with spaces until it reaches `setw(width)`. It doesn't know how the console will render the characters. – Bo Persson Apr 16 '18 at 14:17
  • I tried the same as @YSC, but I have the same problem, where a question mark is printed instead of the infinity sign. I also tried to change my main program (which uses a std::wofstream now), but there I ran into [this problem](https://stackoverflow.com/questions/3950718/wrote-to-a-file-using-stdwofstream-the-file-remained-empty). I am on a linux system where I am not allowed to install anything, so I may just drop it and use "infi" instead of the unicode. – user119879 Apr 16 '18 at 14:51
  • answer depends on operating system and compiler – Barmak Shemirani Apr 16 '18 at 19:06

0 Answers0