问题
I'm intending to reset all output flags to default on the lines where I end using the resetiosflags
function. It provides erroneous output when I attempt to do it in this manner, contrary to my expectations.
#include <iostream>
#include <iomanip>
using namespace std;
int
main()
{
bool first;
int second;
long third;
float fourth;
float fifth;
double sixth;
cout << "Enter bool, int, long, float, float, and double values: ";
cin >> first >> second >> third >> fourth >> fifth >> sixth;
cout << endl;
// ***** Solution starts here ****
cout << first << " " << boolalpha << first << endl << resetiosflags;
cout << second << " " << showbase << hex << second << " " << oct << second << endl << resetiosflags;
cout << third << endl;
cout << showpos << setprecision(4) << showpoint << right << fourth << endl << resetiosflags;
cout << scientific << fourth << endl << resetiosflags;
cout << setprecision(7) << left << fifth << endl << resetiosflags;
cout << fixed << setprecision(3) << fifth << endl << resetiosflags;
cout << third << endl;
cout << fixed << setprecision(2) << fourth << endl << resetiosflags;
cout << fixed << setprecision(0) << sixth << endl << resetiosflags;
cout << fixed << setprecision(8) << fourth << endl << resetiosflags;
cout << setprecision(6) << sixth << endl << resetiosflags;
// ***** Solution ends here ****
cin.get();
return 0;
}
My known alternative is de-flagging them individually by restating them, but that seems superfluous.
回答1:
/*unspecified*/ resetiosflags( std::ios_base::fmtflags mask );
std::resetiosflags()
is a manipulator intended to be used in an expression such as out << resetiosfloags( flags )
. Presumably what you're doing is passing in a function pointer, which gets selected by the overload of std::operator<<
that takes a boolean and prints 1.
But std::resetiosflags()
takes a format flags as a parameter which the precision can't be manipulated with. std::ios_base::boolalpha
can, however:
std::cout << ... << std::resetiosflags(std::ios_base::boolalpha);
There's also std::noboolalpha
std::cout << ... << std::noboolalpha;
But if you need to reset the precision to its default you can just create your own manipulator for that. You can also use Boost IO State Saver.
来源:https://stackoverflow.com/questions/28257527/resetting-output-flags-in-c