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?

6
  • Hello and welcome on StackOverflow. Nice first question. Commented Apr 16, 2018 at 13:29
  • 2
    Possible duplicate of cout << setw doesn't align correctly with åäö Commented Apr 16, 2018 at 13:41
  • 1
    Although I tested it with your specific case and did not get a satisfying result. Commented Apr 16, 2018 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. Commented Apr 16, 2018 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. 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. Commented Apr 16, 2018 at 14:51

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.