读书人

求解难题:ostream自定义的格式控制符,

发布时间: 2012-03-24 14:00:46 作者: rapoo

求解难题:ostream自定义的格式控制符,并且使之暂时有效
例如ostream的setw(int width)是暂时有效的,不知其内部如何实现.
例如我添加一个格式控制符OS_ERROR
ostream &OS_ERROR(ostream &myos)
{
SetColor(ERROR_COLOR);//自定义函数设置文本颜色为红色
ostream &os=myos < < "[FAILD] " < <flush;
SetColor(BEFORE_COLOR);//恢复文本颜色,如果不这样,其它输出文字也继续为红色
return os;
}
这样可以cout < <OS_ERROR;//输出一个红色的[FAILD]
但是我想实现cout < <红色控制符号 < < "信息 " < < "其它 ";
如果默认文本颜色为白色,则输出为红色的 "信息 ",而 "其它 "为白色.也就是说红色控制符号只与临近的输出起作用,像setw一样.请高手们发表一下见解...

[解决办法]
struct _Setw { int _M_n; };

/**
* @brief Manipulator for @c width.
* @param n The new width.
*
* Sent to a stream object, this manipulator calls @c width(n) for
* that object.
*/
inline _Setw
setw(int __n)
{
_Setw __x;
__x._M_n = __n;
return __x;
}

template <typename _CharT, typename _Traits>
inline basic_istream <_CharT,_Traits> &
operator> > (basic_istream <_CharT,_Traits> & __is, _Setw __f)
{
__is.width(__f._M_n);
return __is;
}
width是一个例外,而且是唯一一个另外。
看看 <标准C++输入输出流与本地化> P132就知道了。

读书人网 >C++

热点推荐