在C ++中重置输出标志 [英] Resetting output flags in C++
问题描述
我打算在使用resetiosflags
函数结束的行上将所有输出标志重置为默认值.当我尝试以这种方式进行操作时,它会提供错误的输出,这与我的预期相反.
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.
推荐答案
/*unspecified*/ resetiosflags( std::ios_base::fmtflags mask );
std::resetiosflags()
是打算在诸如out << resetiosfloags( flags )
之类的表达式中使用的操纵器.大概您正在做的是传入一个函数指针,该指针由std::operator<<
的重载选择,该重载采用布尔值并输出1.
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.
但是std::resetiosflags()
将格式标志用作无法操纵精度的参数.但是,std::ios_base::boolalpha
可以:
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);
还有std::noboolalpha
std::cout << ... << std::noboolalpha;
但是,如果您需要将精度重置为默认值,则可以为此创建自己的操纵器.您还可以使用提升IO状态保护程序.
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.
这篇关于在C ++中重置输出标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!