15.1.3 流式输出(3)
通过clear()方法重置流的错误状态:
- cout.clear();
控制台输出流的错误检查不如文件输入输出流的错误检查频繁。这里讨论的方法也适用于其他类型的流,后面讨论每一种类型的时候都会回顾这些方法。
4. 输出操作算子
流有一项独特的特性,那就是放入数据滑槽的内容并非仅限于数据。C++(www.cppentry.com)流还能识别操作算子(manipulator),操作算子是能够修改流行为的对象,而不是(或者额外提供)流能够操作的数据。
您已经看到了一个操作算子:endl。endl操作算子封装了数据和行为。endl算子要求流输出一个行结束序列,并且刷新缓冲。下面列出了其他有用的操作算子,大部分定义在<ios>和<iomanip>标准头文件中。列表后面的例子展示了如何使用这些操作算子:
boolalpha和noboolalpha:要求流将bool值输出为true和false(boolalpha)或1和0(noboolalpha)。默认行为是noboolalpha。
hex、oct和dec:分别以十六进制、八进制和十进制输出数字。
setprecision:设置输出小数时的小数位数。这是一个参数化的操作算子(也就是说这个操作算子接受一个参数)。
setw:设置输出数值数据的字段宽度。这是一个参数化的操作算子。
setfill:当数字宽度小于指定宽度的时候,设置用于填充的字符。这是一个参数化的操作算子。
showpoint和noshowpoint:对于不带小数部分的浮点数,强制流总是显示或总是不显示小数点。
[C++(www.cppentry.com)11] put_money:向流写入一个格式化的货币值。
[C++(www.cppentry.com)11] put_time:向流写入一个格式化的时间值。
下面的例子通过这些操作算子自定义输出。这个例子还使用了第14章讨论的locale概念。
- // Boolean values
- bool myBool = true;
- cout << "This is the default: " << myBool << endl;
- cout << "This should be true: " << boolalpha << myBool << endl;
- cout << "This should be 1: " << noboolalpha << myBool << endl;
-
- // Simulate "%6d" with streams
- int i = 123;
- printf("This should be '123': %6d\n", i);
- cout << "This should be '123': " << setw(6) << i << endl;
- // Simulate "%06d" with streams
- printf("This should be '000123': %06d\n", i);
- cout << "This should be '000123': " << setfill('0') << setw(6) << i << endl;
-
- // Fill with *
- cout << "This should be '***123': " << setfill('*') << setw(6) << i << endl;
- // Reset fill character
- cout << setfill(' ');
-
- // Floating point values
- double dbl = 1.452;
- double dbl2 = 5;
- cout << "This should be ' 5': " << setw(2) << noshowpoint << dbl2 << endl;
- cout << "This should be @@1.452: " << setw(7) << setfill('@') << dbl << endl;
-
- // Format numbers according to your location
- cout.imbue(locale(""));
- cout << "This is 1234567 formatted according to your location: " << 1234567 << endl;
-
- // C++(www.cppentry.com)11 put_money:
- cout << "This should be a money amount of 1200, "
- << "formatted according to your location: "
- << put_money("120000") << endl;
-
- // C++(www.cppentry.com)11 put_time:
- time_t tt;
- time(&tt);
- tm t;
- localtime_s(&t, &tt);
- cout << "This should be the current date and time "
- << "formatted according to your location: "
- << put_time(&t, "%c") << endl;
-
- 代码取自Manipulator\Manipulator.cpp
如果您不关心操作算子的概念,通常也能应付过去。流通过precision()这类方法提供了大部分相同的功能。例如,以如下这行代码为例:
- cout << "This should be '1.2346': " << setprecision(5) << 1.234567 << endl;
这一行代码可以转换为方法调用:- cout.precision(5);
- cout << "This should be '1.2346': " << 1.23456789 << endl;
-
- 代码取自Manipulator\Manipulator.cpp
更详细信息请参阅Wrox网站上的标准库参考资源。