Control ofstream output field width

Hi,

I have to output a series of data, I have to control the width of parts of my data. like following:
1
2
3
4
5
6
7
8
double a[] = {1.0, 2.0, 3.0};
double b[] = {1.5, 2.5, 3.5};
ofsteam myfile("result.txt");

for(int i=0; i<3; i++) {
   myfile.width(5);
   myfile << i+1 << " : " << a[i] << " - " << b[i] << end;
}

I only want to fix the width of a[i], b[i], but let the rest to be output normally.

Could anyone please tell me how I can make it? Thanks!
Last edited on
Yes, you include <iomanip>. Then you use std::setw(size_t).
1
2
3
4
5
6
#include <iomanip>

...

myFile<< i + 1<< " : "<< setw(10)<<a[i]<<b[i]<<endl;


Great that works, thanks! But I still have one question. Assuming I have some data with irregular length (different precision), like:
1
2
double a[] = {1.0, 2.0852695, 3.036, 0.035874};
double b[] = {1.5, 2.5, 3.5, 4.5};


How can I fix the level of precision? for example, I want 2 digits after decimal point for each element.
The function .precision actually controls the total length of data, which is not what I want.
Thanks in advance!
Last edited on
You mean like this?
myFile << std::fixed << std::setprecision(2);
Last edited on
Thanks for the reply. It works! But there is something I want to understand:

It seems that when I put once the << std::fixed << std::setprecision(2); all code after will follow the format. How can I make it work only for a block of code, not all of the rest of the code following the function?
Look at their documentation. They modify "state".

Therefore:
1. Store state
2. Change state
3. Use stream
4. Restore state

For added fun create a simple class that stores and sets in constructor and restores in destructor.
Last edited on
Topic archived. No new replies allowed.