0
点赞
收藏
分享

微信扫一扫

cout.setf() 与 cout.precision()


大家都知道 :cout.setf()是用来设置位的,cout.precision()是用来设置精度的,但具体如何操作想必难倒一批人!



std::ios_base::setf   或者 std::ios::setf

C++

Input/output library

std::ios_base

fmtflags setf( fmtflags flags );

(1)  

fmtflags setf( fmtflags flags, fmtflags mask );

(2)  

Sets the formatting flags to specified settings.


1) Sets the formatting flags to flags


2) Clears the formatting flags under mask, and sets the cleared flags to those specified by flags. Essentially the following operation is performed  (flags & mask) where fl defines the state of internal formatting flags.


Parameters

flags, mask - new formatting setting. mask defines which flags can be altered, flags defines which flags of those to be altered should be set (others will be cleared). Both parameters can be a combination of the following constants:

Constant Explanation

dec use decimal base for integer I/O

oct use octal base for integer I/O

hex use hexadecimal base for integer I/O

basefield dec|oct|hex|0. Useful for masking operations    由此向上四个是一组

left left adjustment (adds fill characters to the right)

right right adjustment (adds fill characters to the left)

internal internal adjustment (adds fill characters to the internal designated point)

adjustfield left|right|internal. Useful for masking operations   由此向上四个是一组

scientific generate floating point types using scientific notation, or hex notation if combined with fixed

fixed generate floating point types using fixed notation, or hex notation if combined with scientific

floatfield scientific|fixed|(scientific|fixed)|0. Useful for masking operations   由此向上3个是一组

boolalpha insert and extract bool type in alphanumeric format

showbase generate a prefix indicating the numeric base for integer output, require the currency indicator in monetary I/O

showpoint generate a decimal-point character unconditionally for floating-point number output

showpos generate a + character for non-negative numeric output

skipws skip leading whitespace before certain input operations

unitbuf flush the output after each output operation

uppercase replace certain lowercase letters with their uppercase

equivalents in certain output output operations




例子:


C/C++ code ?
#include <iostream>
using namespace std;

int main () {
cout.setf ( ios::hex, ios::basefield ); // set hex as the basefield
cout.setf ( ios::showbase ); // activate showbase
cout << 100 << endl;
cout.setf ( 0, ios::showbase ); // deactivate showbase
cout << 100 << endl;
return 0;
}

输出:

0x64

64


setprecision:

C/C++ code ?
#include <iostream>
#include <iomanip>
using namespace std;

int main () {
double f =3.14159;
cout << setprecision (5) << f << endl;
cout << setprecision (9) << f << endl;
cout << fixed;
cout << setprecision (5) << f << endl;
cout << setprecision (9) << f << endl;
return 0;
}

输出:

3.1416
3.14159
3.14159
3.141590000


参考网址:

​​http://en.cppreference.com/w/cpp/io/ios_base/setf ​​


举报

相关推荐

0 条评论