1

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?

Community
  • 1
  • 1
nullByteMe
  • 6,141
  • 13
  • 62
  • 99
  • What output are you expecting? The second number your are sending to `cout` is not in the problem statement and you're outputting a space between the first and second numbers. – Captain Obvlious Jan 25 '15 at 23:13
  • 1
    shouldn't you say `setw(15)` instead? – rodrigo Jan 25 '15 at 23:14
  • @CaptainObvlious the numbers produced are random, so I just provided a random number. I'm expecting `24.01427 5252.25152` – nullByteMe Jan 25 '15 at 23:14
  • @rodrigo, that fixed my problem, but why doesn't `setw(5)` provide any spaces between the numbers? – nullByteMe Jan 25 '15 at 23:16
  • Try using `setw(15)` before the first number. – Mats Petersson Jan 25 '15 at 23:16
  • `setw()` determines how much space the number should take up (at least, so if you print 10010191001121.1234, then it may well take up more - and thus not give you any space between. – Mats Petersson Jan 25 '15 at 23:17
  • No, `setw(5)` will extend the width used by the next number up to 5 characters, but given that it uses about 10 by itself, it does nothing useful. If you want a space then just `<< ' '`. – rodrigo Jan 25 '15 at 23:17
  • @rodrigo got it, thank you! I'm new to c++, obviously haha – nullByteMe Jan 25 '15 at 23:18

1 Answers1

4

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523