I have just started learning C++. I have used printf() with C in the past to format numbers. this doesn't seem to be favoured in modern C++.
I find using setw() and setprecision() seperately rather clumsy, particularly if you have a table with varying widths and precisions. I wondered if there was a way of combining them similar to printf(). I was thinking something along the lines of format(setw,setprecision).
Width is not a sticky manipulator in C++ but precision is, so you can fix precision upto a particular point until you want to change it:
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
cout<<setprecision(3);
double x = 11.089, y = 3.329;
cout << x << " " << y << '\n';
}
However it is not possible to do this for width but you can create a custom data-type that overloads << with a fixed width. I quite like the example here: http://stackoverflow.com/questions/7248627/setting-width-in-c-output-stream
And you can add the degree of setprecision to this class and combine the two
Thank you bird1234 and gunnerfunner for your responses. I know I can use printf() but it is a C function, which is quite flexible and I'm surprised it it's not replicated in some way. In my experience, the width of output and its precision usually go together. Being new to C++, I wondered if I was missing something, or if someone had written a function to replicate printf() our the print using in Basic.
I can live with it, but I just find it to be a surprising omission in C++ and its replacement to be somewhat clumsy.