默认情况下各字段的输出:
#include<iostream>
using std::cout;
int main()
{
cout << "12345678901234567890\n";
char ch = 'K';
int t = 242;
cout << ch << ":\n"; //利用:观察字段宽度
cout << t << ":\n";
cout << -t << ":\n";
double f1 = 1.2000;
cout << f1 << ":\n";
cout << (f1 + 1.0 / 9.0) << ":\n"; //利用1.0 / 9.0 生成无穷小数
double f2 = 1.6E2;
cout << f2 << ":\n";
f2 += 1.0 / 9.0;
cout << f2 << ":\n";
cout << (f2 * 1.0e4) << ":\n";
double f3 = 1.2e-4;
cout << f3 << ":\n";
cout << f3 / 10 << ":\n";
system("pause");
return 0;
}
1.修改默认的计数系统。
控制整数以十进制,十六进制,八进制输出,分别使用dec、hex、oct控制符
#include<iostream>
using std::cout;
using std::hex; using std::oct; using std::dec;
int main()
{
cout << "Enter an integer: ";
int n;
cin >> n;
cout << "n n * n\n";
cout << hex;
cout << n << " " << n * n << " (hexadecimal)\n";
oct(cout);
cout << n << " " << n * n << " (octal)\n";
cout << dec << n << " " << n * n << " (decimal)\n";
system("pause");
return 0;
}
2.利用width()方法调整字段宽度(右对齐)
int width(); 返回字段宽度的当前设置
int width(int i); 将字段宽度设置为i个空格,并返回以前的字段宽度值
width()方法只影响将显示的下一个项目
#include<iostream>
using std::cout;
int main()
{
int w = cout.width(30); //返回的是以前的字段宽度,所以w的值为0
cout << "default field width = " << w << ":\n";
cout.width(5);
cout << "N" << ":";
cout.width(8);
cout << "N * N" << ":\n";
for (long i = 1; i <= 100; i *= 10)
{
cout.width(5);
cout << i << ':';
cout.width(8);
cout << i * i << ':' << '\n';
}
system("pause");
return 0;
}
3.利用fill()方法修改填充部分
默认情况下,cout用空格填充字段中未被使用部分,cout.fill('*')将填充字符改为星号,而且一直有效,直到更改为止
#include<iostream>
using std::cout;
int main()
{
cout.fill('*');
const char* staff[1] = { "hello world" };
cout.fill('*');
cout.width(15);
cout << staff[0] << std::endl;
system("pause");
return 0;
}
4.用precision()方法设置精度
#include<iostream>
using std::cout;
int main()
{
float f = 1.23456789f;
cout << f << std::endl;
cout.precision(2);
cout << f << std::endl;
system("pause");
return 0;
}