c++ - Switching between different numeric formatting styles in an iostream -


i have c++ program writing output iostream, need switch between different numeric styles, e.g. between scientific , non-scientific. here i'm looking at:

#include <iostream> #include <iomanip>  using namespace std;  int main() {     cout << setw(2) << 1 << ' ' << setw(4) << 0.25 << ' ';     cout.width(6);     cout.setf(ios::scientific, ios::floatfield);     cout << 3.0 << ' ';     cout.unsetf(ios::floatfield);     cout << 4.0 << ' ';     cout.setf(ios::scientific, ios::floatfield);     cout << 3.0 << ' ';     cout.unsetf(ios::floatfield);     cout << 4.0 << endl;     return 0; } 

is ridiculousness required? looks terrible. comparison, looks more sane in c:

#include <stdio.h>  int main() {     printf("%2d %4g %6e %6g %6e %6g\n", 1, 0.25, 3.0, 4.0, 3.0, 4.0);     return 0; } 

is there way use iostream in c++ make easier read?

this may overkill implement light weight types did custom formatting

struct scientific {   double value;   scientific(double value) : value(value) { }  };  ostream& operator<< (ostream &o, const scientific& p) {   o.setf(ios::scientific, ios::floatfield);   o << p.value;   o.unsetf(ios::floatfield);   return o; } 

then scientific notation specified annotation value instead of multiple lines

cout << 1 << ' ' << scientific(2.0) << ' ' << endl; 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -