输入输出流(一)——格式控制细节探讨

来源:互联网 发布:玻璃胶 白色透明知乎 编辑:程序博客网 时间:2024/04/30 17:49

背景:

在学习输入输出流的时候,老师布置了一道习题:

从键盘输入一批数值,要求保留3位小数,在输出时上下行小数点对齐。
①用控制符控制输出格式;
②用流成员函数控制输出格式。

题目并不是很难。但是我在写代码的时候发现稍微动一下一些“元素”的位置,输出结果就可能出错。于是我查阅了www.cplusplus.com

查阅与发现:

Stream manipulators
Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example:
 
cout << boolalpha;


They are still regular functions and can also be called as any other function using a stream object as argument, for example:
 
boolalpha (cout);


Manipulators are used to change formatting parameters on streams and to insert or extract certain special characters.

首先我找到了这样一段英文。manipulator指的便是题目里面所说的“控制符”。这段英文的大概意思如下:“控制符”是一种特殊的函数,它们在使用中与 流提取 以及 流插入运算符相连。它们仍然是函数,因此可以像其他函数一样,以一个流对象为形参进行调用。“控制符”的作用是改变流的格式(参量),并且插入或提取特殊字符。

总结来说,大部分manipulator可以像函数一样调用,但是形参一定要加上自己想修饰的流对象。
double a = 1.222222;fixed();cout<<a<<endl;
(代码报错)
double a = 1.222222;fixed(cout);cout<<a<<endl;
double a = 1.222222;cout<<fixed<<a<<endl;

(代码正确)
但是应该注意的是,有一些manipulator只能与流插入和流提取运算符连用。比如 以下这些。
选择setprecision进去看一下。

Behaves as if member precision were called with n as argument on the stream on which it isinserted/extracted as a manipulator (it can be inserted/extracted on input streams or output streams).
注意红色字体,当它被插入或者提取的时候,作用与cout的成员函数precision相同。从这句话中我们可以推断,setprecision这个manipulator是不可以像普通函数一样调用的。
double a = 1.222222;setprecision(3);cout<<fixed<<a<<endl;

上面的代码虽然不会报错(VC6.0),但是setprecision不发挥任何作用。
double a = 1.222222;cout<<fixed<<setprecision(3)<<a<<endl;

结果为1.222。正确。
setprecision 包含在头文件iomanip.h中,所以我们推断iomanip.h中的所有操作符均不可以放在流提取流插入运算符的外面使用。

iomanip.h头文件中包含哪些manipulator呢。


总结:

第一次写博客,感觉发现了很多,其实后来写出来并不多,而且在写的过程中发现了更多的不懂的,督促我去查阅更多的资料。虽然到目前很多东西我还都不明白,不过我已经尝到了刘未鹏先生所说的写博客的好处。坚持吧。
原创粉丝点击