标签:
这篇文章主要讲解如何在C++中使用cout进行高级的格式化输出操作,包括数字的各种计数法(精度)输出,左或右对齐,大小写等等。通过本文,您可以完全脱离scanf/printf,仅使用cout来完成一切需要的格式化输入输出功能(从非性能的角度而言)。更进一步而言,您还可以在<sstream>、<fstream>上使用这些格式化操作,从而代替sprintf和fprintf函数。为方便描述,下文仅以cout为例进行介绍。#include <iomanip> #include <iostream>
#include <iomanip> #include <iostream> using namespace std; int main(void) { cout.flags(ios::left); //左对齐 cout << setw(10) << -456.98 << "The End" << endl; cout.flags(ios::internal); //两端对齐 cout << setw(10) << -456.98 << "The End" << endl; cout.flags(ios::right); //右对齐 cout << setw(10) << -456.98 << "The End" << endl; return 0; }
#include <iomanip> #include <iostream> using namespace std; int main(void) { cout << left << setw(10) << -456.98 << "The End" << endl; //左对齐 cout << internal << setw(10) << -456.98 << "The End" << endl; //两端对齐 cout << right << setw(10) << -456.98 << "The End" << endl; //右对齐 return 0; }
-456.98The End
这里要额外说明的一点是,setw函数会用当前的填充字符控制对齐位置,默认的填充字符是空格。可以通过<iomanip>的setfill来设置填充字符,比如下面的代码用字符“0”作为填充字符:
标签:
原文地址:http://my.oschina.net/lieefu/blog/523953