C++的cin/cout高阶格式化操作_开发平台子站_IT专家网II
来源:百度文库 编辑:神马文学网 时间:2024/05/23 19:10:26
C++的cin/cout高阶格式化操作
作者: 佚名, 出处:IT专家网, 责任编辑: 谢妍妍, 2010-09-08 10:40这篇文章主要讲解如何在C++中使用cin/cout进行高级的格式化输出操作,包括数字的各种计数法(精度)输出,左或右对齐,大小写等等。通过本文,您可以完全脱离scanf/printf,仅使用cin/cout来完成一切需要的格式化输入输出功能(从非性能的角度而言)。更进一步而言,您还可以在、上使用这些格式化操作,从而代替sscanf/sprintf和fscanf/fprintf函数。为方便描述,下文仅以cin/cout为例进行介绍。
四、小数
小数可分为两种格式类型,一种是定点表示“ios::fixed”(不带指数域),另一种是科学计数法表示“ios::scientific”(带指数域)。与
01 #include
02 #include
03 using namespace std;
04 int main(void) {
05 cout.setf(ios::fixed);
06 cout << setprecision(0) << 12.05 << endl;
07 cout << setprecision(1) << 12.05 << endl;
08 cout << setprecision(2) << 12.05 << endl;
09 cout << setprecision(3) << 12.05 << endl;
10 cout.setf(ios::scientific, ios::floatfield);
11 cout << setprecision(0) << 12.05 << endl;
12 cout << setprecision(1) << 12.05 << endl;
13 cout << setprecision(2) << 12.05 << endl;
14 cout << setprecision(3) << 12.05 << endl;
15 return 0;
16 }
结果:
12
12.1
12.05
12.050
1.205000e+001
1.2e+001
1.21e+001
1.205e+001
需要注意的是,有时会因为机器的精度问题导致四舍五入的结果不正确。这种问题一般需要手动修正,见如下代码示例:
以下是代码片段:
1 #include
2 #include
3 using namespace std;
4 int main(void) {
5 cout << fixed << setprecision(1) << 2.05 << endl;
6 cout << fixed << setprecision(1) << 2.05 + 1e-8 << endl;
7 return 0;
8 }
结果:
2.0
2.1
四、字符串
字符串的输出处理主要是对齐,这一点在第二部分已经介绍过了,下面主要介绍字符串的输入方法。为了方便起见,我们使用
01 #include
02 #include
03 #include
04 using namespace std;
05 int main(void) {
06 string str1, str2;
07 getline(cin, str1);
08 cin >> str2;
09 cout << str1 << endl << str2 << endl;
10 return 0;
11 }
输入:
abc
abc
结果:
abc
abc
五、缓冲区
由于调用系统函数在屏幕上逐个显示字符是很慢的,因此cin/cout为了加快速度使用缓冲区技术,粗略的讲就是暂时不输出指定的字符,而是存放在缓冲区中,在合适的时机一次性输出到屏幕上。如果单纯使用C++的输入/输出流来操作字符是不存在同步的问题的,但是如果要和C标准库的stdio库函数混合使用就必须要小心的处理缓冲区了。如果要与scanf和printf联合使用,务必在调用cout前加上cout.sync_with_stdio(),设置与stdio同步,否则输出的数据顺序会发生混乱。
flush和endl都会将当前缓冲区中的内容立即写入到屏幕上,而unitbuf/nounitbuf可以禁止或启用缓冲区。示例代码如下:
以下是代码片段:
1 #include
2 #include
3 using namespace std;
4 int main(void) {
5 cout << 123 << flush << 456 << endl;
6 cout << unitbuf << 123 << nounitbuf << 456 << endl;
7 return 0;
8 }
结果:
123456
123456
六、综合使用
示例代码:
以下是代码片段:
01 #include
02 #include
03 #include
04 using namespace std;
05 struct COMMODITY { string Name; int Id; int Cnt; double Price; };
06 int main(void) {
07 COMMODITY cmd[] = {
08 {"Fruit", 0x101, 50, 5.268},
09 {"Juice", 0x102, 20, 8.729},
10 {"Meat", 0x104, 30, 10.133},
11 };
12 cout << left << setw(8) << "NAME" << right << setw(8) << "ID";
13 cout << right << setw(8) << "COUNT" << right << setw(8) << "PRICE" << endl;
14 for (int i = 0; i < sizeof(cmd) / sizeof(cmd[0]); ++i) {
15 cout << left << setw(8) << cmd[i].Name;
16 cout << right << hex << showbase << setw(8) << cmd[i].Id;
17 cout << dec << noshowbase << setw(8) << cmd[i].Cnt;
18 cout << fixed << setw(8) << setprecision(2) << cmd[i].Price << endl;
19 }
20 return 0;
21 }
结果:
NAME ID COUNT PRICE
Fruit 0x101 50 5.27
Juice 0x102 20 8.73
Meat 0x104 30 10.13