Buqian Zheng
Buqian Zheng

Reputation: 341

what's the range of the formatted output of `cout`

In my program, there will be two lines of output: numbers in the first line are integers less than 1000; numbers in the second line are floats between 0 and 10. The format of the output I want is like:

right format

and here is how I try (all outputs are the last four lines): case 1 - 5

  1. output without format; in the picture we can see the numbers that should be printed
  2. line 1 without format and line 2 with format numbers in line 1; only the first one is right, and the number that is bigger than 100 is in scientific notation
  3. both lines with format just like case 2, and <<setw(3)<<setfill('0') seems only works for one time to change 43 to 043, and then it won't work any more
  4. With noshowpoint added. If i print *(p + 2)alone, it always prints 118with or without format. But if I print *(p + 2) in the for loop, the output is still 1.2e+002 except for the first one. But if I print the number 118 directly, the output is right.

So, which part of my code is wrong? And what is the right way to output the answer in right format?

Upvotes: 1

Views: 153

Answers (2)

Roman Pustylnikov
Roman Pustylnikov

Reputation: 1932

Well, for the third, you set showpoint but never unset it with the noshowpoint, hence the next lines issue.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    double x[4]= {43.0,118.0,9.0,5.0};
    double y[4] = {9.5, 9.0, 8.5, 8.0};
    // your code goes here
    for (int i=0; i< 4; i++)
    {
      cout<<noshowpoint<<setprecision(3)<<setw(3)<<setfill('0')<<(x[i]) <<" ";
      cout<<showpoint<<setprecision(2)<<y[i] << endl;
    }
    return 0;
}

gives the desired output.

Just pay attention that you set the showpoint and setprecision manipulators for stream, not for the single output.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385204

Indeed, not all IO Formatting Manipulators are persistent. Some of them, like std::setw only take effect on the next operation, then they expire. There's nothing "wrong" with your code; you just need to use the manipulator again. Refer to your favourite C++ standard library documentation to check the persistence of each manipulator that you use.

Upvotes: 2

Related Questions