C++ cout Controlling format

Introduction

The flags(), setf(), and unsetf() methods set or retrieve a set of format flags maintained within the istream or ostream object.

The I/O Stream Format Flags

FlagDescription
boolalpha Displays bool as either true or false rather than 1 or 0.
dec Reads or writes integers in decimal format (default).
fixed Displays floating point in fixed point as opposed to scientific (default).
hex Reads or writes integers in hexadecimal.
leftDisplays output left justified (i.e., pads on the right).
oct Reads or writes integers in octal.
right Displays output right justified (i.e., pads on the left).
scientific Displays floating point in scientific format.
showbaseDisplays a leading 0 for octal output and leading 0x for hexadecimal output.
showpointDisplays a decimal point for floating-point output even if the fractional portion is 0.
skipws Skips over whitespace when reading using the extractor.
unitbuf Flushes output after each output operation.
uppercaseReplaces lowercase letters with their uppercase equivalents on output.

The following code shows how to display numbers in hexadecimal format:

// read the current format flags 
ios_base::fmtflags prevValue = cout.flags(); 

// clear the decimal flag 
cout.unsetf(cout.dec); /*from  ww w. j av  a 2  s . co  m*/

// now set the hexadecimal flag 
cout.setf(cout.hex); 

// call flags() to restore the format flags to their previous value 
cout.flags(prevValue);



PreviousNext

Related