Home c++ setw sets different line widths

setw sets different line widths

Author

Date

Category

Hello!
There is a table of some string variables (string ). It is necessary to display this table in an adequate formatted form. The problem is that when using the setw () manipulator, lines of different lengths take up different field widths, not a fixed one.

# include & lt; string & gt;
#include & lt; iostream & gt;
#include & lt; iomanip & gt;
using namespace std;
int main ()
{
 string one = "One", two = "Two", eight = "Eight";
 cout & lt; & lt; setw (10) & lt; & lt; one & lt; & lt; endl;
 cout & lt; & lt; setw (10) & lt; & lt; two & lt; & lt; endl;
 cout & lt; & lt; setw (10) & lt; & lt; eight & lt; & lt; endl;
 return 0;
}

Expected output:

one
  two
eight

What really comes out:

one
  two
eight

Actually the question is – why is this? And how can you still display lines aligned – one below the other?


Answer 1, authority 100%

Eh. Apparently these are internationalization and utf-8 issues.

The fact is that C++ does not know about utf-8, and calculates the field width in bytes, and not in real characters. And for utf-8, the number of bytes is not equal to the number of characters. Please note that your field width turned out to be not 10, but less – the text "One" in utf-8 takes more than four bytes, so the number of missing up to 10 bytes is less.

Try going wide lines:

wstring one = L "One", two = L "Two", eight = L "Eight";
wcout & lt; & lt; setw (10) & lt; & lt; one & lt; & lt; endl;
wcout & lt; & lt; setw (10) & lt; & lt; two & lt; & lt; endl;
wcout & lt; & lt; setw (10) & lt; & lt; eight & lt; & lt; endl;

If you are on Windows, you will need to do some acrobatics to get the console to understand wide strings correctly. Under Linux, it seems to be enough to cast a spell at the beginning of the program

setlocale (LC_ALL, "");

Note that the console I / O of the application must be either completely “narrow” or completely “wide”: you can no longer switch after the first character printed.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions