使用cout输出时,想要控制输出的格式,比如显示两位小数、显示十六进制数、全部显示大写字母、输出十六进制数时带0x,这些都可以用标准函数库std中的setf()来完成,即使用cout.setf()。当然,如果显示十六进制数,也可以使用std::hex来控制。
下面对函数cout.setf()原型进行讲解和给出两个简单例子,第一个例子是显示两位小数,第二个例子是显示固定位数十六进制数,不足位数补零。
1.1 cout.setf()函数原型
fmtflags __CLR_OR_THIS_CALL setf(fmtflags _Newfmtflags, fmtflags _Mask)
{ // merge in format flags argument under mask argument
ios_base::fmtflags _Oldfmtflags = _Fmtfl;
_Fmtfl = (fmtflags)(((int)_Fmtfl & (int)~_Mask)
| ((int)_Newfmtflags & (int)_Mask & (int)_Fmtmask));
return (_Oldfmtflags);
}
函数fmtflags setf(fmtflags _Newfmtflags, fmtflags _Mask)有两个原型,一个为一个参数的原型,另一个是两个参数的原型,博主使用的是后者。
其中,函数setf()两个原型参数讲解如下表所示
setf(long, long)的参数
第二个参数 | 第一个参数 | 含义 |
---|---|---|
ios_base::basefiled | ios_base::dec | 使用基数10 |
ios_base::basefiled | ios_base::oct | 使用基数8 |
ios_base::basefiled | ios_base::hex | 使用基数16 |
ios_base::floatfiled | ios_base::fixed | 使用定点计数法 |
ios_base::floatfiled | ios_base::scientific | 使用科学计数法 |
ios_base::adjustfiled | ios_base::left | 使用左对齐 |
ios_base::adjustfiled | ios_base::right | 使用右对齐 |
ios_base::adjustfiled | ios_base::internal | 符号或基数前缀左对齐,值右对齐 |
1.2示范例子1(输出两位小数点示例)
#include <iostream>
#include <Windows.h>
int main()
{
using std::cout;
using std::endl;
using std::ios_base;
cout.setf(ios_base::fixed, ios_base::floatfield); //使用定点计数法,精度指的是小数点后面的位数,而不是总位数
cout.setf(ios_base::showpoint); //显示小数点后面的0
cout.precision(2); //使用定点计数法,显示小数点后面位数精度
cout << 9.66666 << "\t" << 1.3 << "\t" << 0.1 << "\t" << 555.0 << "\t" << 8.0 << "\t" << 777444.0 << endl;
system("pause");
return 0;
}
1.3示范例子2(输出十六进制示例,也可以用std::hex显示十六进制数)
#include <iostream>
#include <Windows.h>
int main()
{
using std::cout;
using std::endl;
using std::ios_base;
//cout.setf(ios_base::basefield, ios_base::hex);
cout.fill('0');//设置有效位空白字符填充字符'0',只对有效位空白字符有效,一般结合cout.width()一起使用,对\t和\n无效
for (int i = 8; i < 12; i++)
{
cout.width(4); //设置宽度只对下一次有效
cout << std::hex << i << "\t" << " ";
}
cout << endl;
system("pause");
return 0;
}