3 回答
TA贡献1842条经验 获得超12个赞
@Chareles:那么根据这个要求,所有的机械手都是粘性的。除了SET,它似乎在使用后被重置。
一点儿没错!而setw似乎行为不同的唯一原因是,格式化的输出操作需要显式地.Width(0)输出流。
setiosflags resetiosflags setbase setfill setprecision setw
setw
setiosflags: Stickyresetiosflags:Stickysetbase: Stickysetfill: Stickysetprecision: Sticky
[no]boolalpha[no]showbase[no]showpoint[no]showpos[no]skipws[no]unitbuf[no]uppercase dec/ hex/ oct fixed/ scientific internal/ left/ right
ws/ endl/ ends/ flush
#include <iostream>
#include <iomanip>
// Private object constructed by the format object PutSquareBracket
struct SquareBracktAroundNextItem
{
SquareBracktAroundNextItem(std::ostream& str)
:m_str(str)
{}
std::ostream& m_str;
};
// New Format Object
struct PutSquareBracket
{};
// Format object passed to stream.
// All it does is return an object that can maintain state away from the
// stream object (so that it is not STICKY)
SquareBracktAroundNextItem operator<<(std::ostream& str,PutSquareBracket const& data)
{
return SquareBracktAroundNextItem(str);
}
// The Non Sticky formatting.
// Here we temporariy set formating to fixed with a precision of 10.
// After the next value is printed we return the stream to the original state
// Then return the stream for normal processing.
template<typename T>
std::ostream& operator<<(SquareBracktAroundNextItem const& bracket,T const& data)
{
std::ios_base::fmtflags flags = bracket.m_str.flags();
std::streamsize currentPrecision = bracket.m_str.precision();
bracket.m_str << '[' << std::fixed << std::setprecision(10) << data << std::setprecision(currentPrecision) << ']';
bracket.m_str.flags(flags);
return bracket.m_str;
}
int main()
{
std::cout << 5.34 << "\n" // Before
<< PutSquareBracket() << 5.34 << "\n" // Temp change settings.
<< 5.34 << "\n"; // After
}
> ./a.out
5.34
[5.3400000000]
5.34
- 3 回答
- 0 关注
- 495 浏览
添加回答
举报