Search code examples
c++setw

Why doesn't setw(n) work here?


Here is my problem:

Given three variables, a, b, c, of type double that have already been declared and initialized, write some code that prints each of them in a 15 position field on the same line, in such away that scientific (or e-notation or exponential notation) is avoided. Each number should be printed with 5 digits to the right of the decimal point. For example, if their values were 24.014268319, 14309, 0.00937608, the output would be:

|xxxxxxx24.01427xxxx14309.00000xxxxxxxx0.00938

NOTE: The vertical bar, | , on the left above represents the left edge of the print area; it is not to be printed out. Also, we show x in the output above to represent spaces-- your output should not actually have x's!

Here is in essence what I'm trying to do:

cout << fixed << setprecision(5) << 24.014268319 << setw(5) << 5252.25151516 << endl;

But this produces the following output:

24.014275252.25152

Clearly I'm not interpreting how to use setw(n) properly, does anyone see what I'm doing wrong here?


Solution

  • The setw(...) I/O manipulator is a little tricky, in that its effect is being reset, i.e. the width is set back to zero, after each call of << (among other things described in the documentation).

    You need to call setw(15) multiple times, like this:

    cout << fixed << setprecision(5) << setw(15) << 24.014268319  << setw(15) << 5252.25151516 << endl;
    

    Demo.