控制输出宽度(占位)
cout.width(int length);
常与 cout.flags(ios::left)
or cout.flags(ios::right)
搭配使用,来控制居左、居右输出
作用域:只能控制下面一句 cout 输出!
例:
string s = "she";
char ch = 'v';
cout.width(5);
cout.flags(ios::right);
cout << s << endl; // __she,起作用
cout << ch << endl; // v,未起作用
控制占位填充字符
cout.fill(char c)
与cout.width(int length)
搭配使用,用字符填充空白
作用域:只能控制下面一句 cout 输出!
例:
cout.fill('0');
cout.width(3);
int a = 1;
int b = 2;
cout << a << endl; // 001
cout << b << endl; // 2
// 如果想要一直保持此格式,可在每一次输出前加一句 cout.width();
for (int i = 0; i < 3; i++)
{
cout.width(3);
cout << i << endl;
}
// 000
// 001
// 002
控制小数输出位数
与cout.flags(ios::fixed);
搭配使用,控制小数输出位数,如果不加cout.flags(ios::fixed);
而仅使用cout.precision(int len);
则任何效果!
cout.precision(int len); // 保留 len 位小数
cout.flags(ios::fixed);
作用域:能控制下面所有的浮点数输出!
例:
float a = 2.4423;
double b = 2.1;
cout.precision(3); // 保留 3 位小数
cout.setf(ios::fixed);
cout << a << endl; // 2.442
cout << b << endl; // 2.100
取消此效果用cout.unsetf(ios::fixed);
输出非负数的正号
cout.flags(ios::showpos);
作用域:能控制下面所有的数字输出!
例:
cout.flags(ios::showpos);
int a1 = 0;
cout << 3.12 << endl; // +3.12
cout << a1 << endl; // +0
取消此效果用cout.unsetf(ios::showpos);
使用 8/10/16 进制输出整数
一般情况下,是默认十进制输出
cout.flags(ios::oct);
cout.flags(ios::dec);
cout.flags(ios::hex);
作用域:能控制下面所有的数字输出!
例:
int a = 12;
cout.flags(ios::oct);
cout << a << end; // 14
cout.flags(ios::dec);
cout << a << end; // 12
cout.flags(ios::hex);
cout << a << end; // c
直接输出数据,不受格式化参量影响
cout.put(char c);
直接输出一个字符,不受流的格式化参量影响
例:
cout.fill('*');
cout.width(3);
cout.put('a') << endl; // a
cout.width(3);
cout << 'a' << endl; // **a
更多
详见官网