Last active
February 28, 2018 07:05
-
-
Save lixingcong/fd1fc424d6ba53446eacb533c1020b6d to your computer and use it in GitHub Desktop.
C++ std cout format example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
using namespace std; | |
void restore_fmt(std::_Ios_Fmtflags fmt) | |
{ | |
cout << "restore flag" << endl; | |
cout.flags(fmt); | |
cout << endl; | |
} | |
int main(int argc, char **argv) | |
{ | |
// backup the default FMT_FLAG | |
std::_Ios_Fmtflags fmt_flag_orig = cout.flags(); | |
double i = 200.123456789; | |
cout << "init val=" << i << endl; | |
cout << endl; | |
cout << "set width" << endl; | |
cout << "|" << 12 << "|" << setw(6) << 12 << "|" << 12 << endl; | |
cout << endl; | |
cout << "set precision" << endl; | |
cout << "|" << i << "|" << setprecision(3) << i << "|" << i << "|" << endl; | |
cout << endl; | |
restore_fmt(fmt_flag_orig); | |
double i1 = 1234567.89; | |
double i2 = 123.987654321; | |
cout << "before set fixed" << endl; | |
cout << "|" << i1 << "|" << i2 << "|" << endl; | |
cout << endl; | |
cout << "set fixed(sticky)" << endl; | |
cout << fixed << "|" << i1 << "|" << i2 << "|" << endl; | |
cout << endl; | |
restore_fmt(fmt_flag_orig); | |
cout << "set scientific(sticky)" << endl; | |
cout << scientific << "|" << i1 << "|" << i2 << "|" << endl; | |
cout << endl; | |
restore_fmt(fmt_flag_orig); | |
cout << "hex|dec|oct (sticky)" << endl; | |
cout << "|dec: " << dec << "|" << 1024 << "|" << -1024 << "|" << endl; | |
cout << "|hex: " << hex << "|" << 1024 << "|" << -1024 << "|" << endl; | |
cout << "|oct: " << oct << "|" << 1024 << "|" << -1024 << "|" << endl; | |
cout << endl; | |
restore_fmt(fmt_flag_orig); | |
cout << "boolean" << endl; | |
cout << boolalpha << "|" << false << "|" << true << "|" << endl; | |
cout << noboolalpha << "|" << false << "|" << true << "|" << endl; | |
cout << endl; | |
restore_fmt(fmt_flag_orig); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: