The code below prints a vector to std::cout
.
struct vect {
double x;
double y;
};
std::ostream& operator<<(std::ostream& os, vect v){
os << "[" << v.x << " " << v.y << "]";
return os;
}
int main(){
vect v = {1.0, 2.0};
std::cout << v << std::endl;
return 0;
}
What would be a good way to control the width/precision of each field? I could hardcode it in operator<<
:
std::ostream& operator<<(std::ostream& os, vect v){
os << "[" << std::setprecision(3) << std::setw(7) << v.x << " " << std::setprecision(3) << std::setw(7) << v.y << "]";
return os;
}
but I would rather want to control it from the outside:
std::cout << std::setprecision(3) << std::setw(7) << v << std::endl;
However I think this would only set the precision and width for the first field of the vector.
What I have in mind is to first "getw" and "getprecision" at the start of operator<<
and then persist them to the other fields. Are there ways to retrieve these things from the stream, and is this basic design based on correct assumptions? (I'm not very confident about how iomanipulators work; I just know to send in std::setw
before the data.)
as covered in comments, setprecision persists, but setw does not.
Supposing you want setw to apply to each individual field in your composition type, but not to the formatting characters around it. To do this, look at the width property, then set it for each of the numeric fields.
#include <iostream>
#include <iomanip>
struct coordinate {
double x;
double y;
};
std::ostream& operator<<(std::ostream& os, coordinate p) {
auto w = os.width();
os << std::setw(0) << "[" // we don't want the width yet
<< std::setw(w) << p.x // set width on specific field
<< " "
<< std::setw(w) << p.y // set width on specific field
<< "]";
return os;
}
int main() {
coordinate value = { 1.000019, 2.000019 };
std::cout << std::setprecision(3) << std::setw(7) << value << std::endl;
std::cout << std::setprecision(6) << std::setw(7) << value << std::endl;
std::cout << std::setprecision(1) << std::setw(3) << value << std::endl;
return 0;
}
output:
[ 1 2] [1.00002 2.00002] [ 1 2]