In a question I found something like this: Write a custom I/O manipulator that prints
123.456%%%
against the following code cout<<setup<<123.456789;
How can this be achieved? I tried this:
#include <iostream>
#include <iomanip>
using namespace std;
std::ostream& setup(std::ostream& os, double num) {
os << std::setprecision(3) << std::fixed << std::showpoint << std::setw(10) << std::left << num << "%%%";
return os;
}
int main() {
//cout << setfill('?') << setw(10) << 2343.0;
cout<<setup<<123.45678;
return 0;
}
Output: 1123.457
Building on @IgorTandetnik's comments above:
The problem:
Your
setupfunction does not match the required signature of I/O manipulators as specified here forfunc- see overloads (18)-(20) ofbasic_ostream& operator<<:Therefore when you use
cout << setup, thesetupfunction is not called (as it was done if it was a proper manipulator).Instead the address of it is converted to
booland displayed as1(this is the initial1that you see).clang even gives a meaniniful warning:
A solution:
You can achieve what you want by using one of the I/O manipulators signatures.
Using the signature of
funcfrom overload (18) is shown below:Output:
Live demo - Godbolt
A side note: Why is "using namespace std;" considered bad practice?.
Update:
If you want to truncate the value and avoid rounding, you can multiply the value by 1000 (for 3 digits precision),
floorit, and then divide by 1000:Output:
Live demo - Godbolt