C++ ios_base类

📅 2026/7/17 11:57:49 👁️ 阅读次数 📝 编程学习
C++ ios_base类

目录

一,_Fmtfl 格式

二,width 格式

三,precision 格式

四,sync_with_stdio函数


ios_base类是输入输出流的一个基础类。

The classios_baseis a multipurpose class that serves as the base class for all I/O stream classes.

一,_Fmtfl 格式

这个成员的每一位,都用来控制流的一个属性

初始化:_Fmtfl = skipws | dec; 初始值是513

读取:flags()

替换:flags(fmtflags _Newfmtflags)

加格式:setf(fmtflags _Newfmtflags)

在给定的mask内设置格式:setf(fmtflags _Newfmtflags, fmtflags _Mask)

相关库函数

_NODISCARD fmtflags __CLR_OR_THIS_CALL flags() const { return _Fmtfl; } fmtflags __CLR_OR_THIS_CALL flags(fmtflags _Newfmtflags) { // set format flags to argument const fmtflags _Oldfmtflags = _Fmtfl; _Fmtfl = _Newfmtflags & _Fmtmask; return _Oldfmtflags; } fmtflags __CLR_OR_THIS_CALL setf(fmtflags _Newfmtflags) { // merge in format flags argument const ios_base::fmtflags _Oldfmtflags = _Fmtfl; _Fmtfl |= _Newfmtflags & _Fmtmask; return _Oldfmtflags; } fmtflags __CLR_OR_THIS_CALL setf( fmtflags _Newfmtflags, fmtflags _Mask) { // merge in format flags argument under mask argument const ios_base::fmtflags _Oldfmtflags = _Fmtfl; _Fmtfl = (_Oldfmtflags & ~_Mask) | (_Newfmtflags & _Mask & _Fmtmask); return _Oldfmtflags; } void __CLR_OR_THIS_CALL unsetf(fmtflags _Mask) { // clear format flags under mask argument _Fmtfl &= ~_Mask; }

示例:

int main() { cout << cout.flags() << endl; cout.setf(ios::unitbuf); cout << cout.flags() << endl; cout.unsetf(ios::unitbuf); cout << cout.flags() << endl; return 0; }

输出

513
515
513

其中ios::unitbuf是常数2

其他的 _Fmtfl 格式:

二,width 格式

width用来控制整数输出的宽度,即占几个字符

相关库函数

_NODISCARD streamsize __CLR_OR_THIS_CALL width() const { return _Wide; } streamsize __CLR_OR_THIS_CALL width(streamsize _Newwidth) { // set width to argument const streamsize _Oldwidth = _Wide; _Wide = _Newwidth; return _Oldwidth; }

示例:

int main() { for (int i = 0; i < 100; i++) { if (i % 10 == 0)cout << endl; cout.width(3); cout << i; } return 0; }

三,precision 格式

precision用来控制浮点数的输出精度

相关库函数

_NODISCARD streamsize __CLR_OR_THIS_CALL precision() const { return _Prec; } streamsize __CLR_OR_THIS_CALL precision(streamsize _Newprecision) { // set precision to argument const streamsize _Oldprecision = _Prec; _Prec = _Newprecision; return _Oldprecision; }

示例:

int main() { cout.precision(3); cout << 1.414213562; return 0; }

输出:1.41

四,sync_with_stdio函数

Sets whether the standard C++ streams are synchronized to the standard C streams after each input/output operation.

相关库函数

static bool __CLRCALL_OR_CDECL sync_with_stdio( bool _Newsync = true) { // set C/C++ synchronization flag from argument _BEGIN_LOCK(_LOCK_STREAM) // lock thread to ensure atomicity const bool _Oldsync = _Sync; _Sync = _Newsync; return _Oldsync; _END_LOCK() }

其中_Sync是私有静态成员

__PURE_APPDOMAIN_GLOBAL static bool _Sync;

这表明所有的流共享一个_Sync成员。