代码:
#include <iostream>
#define ECHO(str) std::cout << str
#define ECHOLN(str) std::cout << str << std::endl
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
double d = 123.456789;
int i = 12345;
std::cout.setf(std::ios::showpos);//正数带 "+"
ECHOLN( d <<" "<< i << "\t(showpos)");
std::cout.setf(std::ios::scientific);//科学计数法显示浮点数
ECHOLN( d <<" "<< i << "\t(showpos|scientific)" );
std::cout.setf(std::ios::showbase);//输出数据前带基数符
std::cout.setf(std::ios::hex);//十六进制显示整数
ECHOLN( d <<" "<< i << "\t(showpos|scientific|showbase|hex)" );//为什么这个不能用????
ECHO( std::hex << std::showbase);
ECHOLN( d <<" "<< i << "\t(showpos|scientific|showbase|hex)" );
ECHOLN("====================================");
ECHOLN("");
ECHO("返回与流相关的当前标志:");
ECHOLN(std::cout.flags());//返回与流相关的当前标志
std::cout.unsetf(std::cout.flags());//返回当前的标志值并清除指定的标志
ECHO("返回与流相关的当前标志:");
ECHOLN(std::cout.flags());//返回与流相关的当前标志
//设置域宽、小数点位数、和填充符
d = 123.456;
double f = 4567.89;
std::cout.setf(std::ios::showpoint);//设置浮点数带小数0
ECHOLN( d << "\t" << f << "\t(showpoint)");
std::cout.setf(std::ios::fixed);//使用定点形式
ECHOLN( d << "\t" << f << "\t(showpoint|fixed)");
std::cout.precision(5);//精度:5位数
ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison)");
std::cout.width(20);//数据宽度:20
ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison|width)");
std::cout.width(20);//数据宽度:20
std::cout.fill('#');
ECHOLN( d << "\t" << f << "\t(showpoint|fixed|precison|width|fill)");
std::cout.width(20);
std::cout.precision(1);
std::cout.fill('&');
ECHOLN(f);
return 0;
}
输出:
+123.457 +12345 (showpos)
+1.234568e+002 +12345 (showpos|scientific)
+1.234568e+002 +12345 (showpos|scientific|showbase|hex)
+1.234568e+002 0x3039 (showpos|scientific|showbase|hex)
====================================
返回与流相关的当前标志:0x1b08
返回与流相关的当前标志:0
123.456 4567.89 (showpoint)
123.456000 4567.890000 (showpoint|fixed)
123.45600 4567.89000 (showpoint|fixed|precison)
123.45600 4567.89000 (showpoint|fixed|precison|width)
###########123.45600 4567.89000 (showpoint|fixed|precison|width|fill)
&&&&&&&&&&&&&&4567.9
--------------------------------
Process exited with return value 0
Press any key to continue . . .
+1.234568e+002 +12345 (showpos|scientific)
+1.234568e+002 +12345 (showpos|scientific|showbase|hex)
+1.234568e+002 0x3039 (showpos|scientific|showbase|hex)
====================================
返回与流相关的当前标志:0x1b08
返回与流相关的当前标志:0
123.456 4567.89 (showpoint)
123.456000 4567.890000 (showpoint|fixed)
123.45600 4567.89000 (showpoint|fixed|precison)
123.45600 4567.89000 (showpoint|fixed|precison|width)
###########123.45600 4567.89000 (showpoint|fixed|precison|width|fill)
&&&&&&&&&&&&&&4567.9
--------------------------------
Process exited with return value 0
Press any key to continue . . .