Reputation: 341
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:
and here is how I try (all outputs are the last four lines): case 1 - 5
<<setw(3)<<setfill('0')
seems only works for one time to change 43 to 043, and then it won't work any morenoshowpoint
added. If i print *(p + 2)
alone, it always prints 118
with 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
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
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