Skip to content

Instantly share code, notes, and snippets.

@lixingcong
Last active February 28, 2018 07:05
Show Gist options
  • Save lixingcong/fd1fc424d6ba53446eacb533c1020b6d to your computer and use it in GitHub Desktop.
Save lixingcong/fd1fc424d6ba53446eacb533c1020b6d to your computer and use it in GitHub Desktop.
C++ std cout format example
#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;
}
@lixingcong
Copy link
Author

output:

init val=200.123

set width
|12|    12|12

set precision
|200.123|200|200|

restore flag

before set fixed
|1.23e+06|124|

set fixed(sticky)
|1234567.890|123.988|

restore flag

set scientific(sticky)
|1.235e+06|1.240e+02|

restore flag

hex|dec|oct (sticky)
|dec: |1024|-1024|
|hex: |400|fffffc00|
|oct: |2000|37777776000|

restore flag

boolean
|false|true|
|0|1|

restore flag

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment