setf2.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // setf2.cpp -- using setf() with 2 arguments to control formatting
  2. #include <iostream>
  3. #include <cmath>
  4. int main()
  5. {
  6. using namespace std;
  7. // use left justification, show the plus sign, show trailing
  8. // zeros, with a precision of 3
  9. cout.setf(ios_base::left, ios_base::adjustfield);
  10. cout.setf(ios_base::showpos);
  11. cout.setf(ios_base::showpoint);
  12. cout.precision(3);
  13. // use e-notation and save old format setting
  14. ios_base::fmtflags old = cout.setf(ios_base::scientific,
  15. ios_base::floatfield);
  16. cout << "Left Justification:\n";
  17. long n;
  18. for (n = 1; n <= 41; n+= 10)
  19. {
  20. cout.width(4);
  21. cout << n << "|";
  22. cout.width(12);
  23. cout << sqrt(double(n)) << "|\n";
  24. }
  25. // change to internal justification
  26. cout.setf(ios_base::internal, ios_base::adjustfield);
  27. // restore default floating-point display style
  28. cout.setf(old, ios_base::floatfield);
  29. cout << "Internal Justification:\n";
  30. for (n = 1; n <= 41; n+= 10)
  31. {
  32. cout.width(4);
  33. cout << n << "|";
  34. cout.width(12);
  35. cout << sqrt(double(n)) << "|\n";
  36. }
  37. // use right justification, fixed notation
  38. cout.setf(ios_base::right, ios_base::adjustfield);
  39. cout.setf(ios_base::fixed, ios_base::floatfield);
  40. cout << "Right Justification:\n";
  41. for (n = 1; n <= 41; n+= 10)
  42. {
  43. cout.width(4);
  44. cout << n << "|";
  45. cout.width(12);
  46. cout << sqrt(double(n)) << "|\n";
  47. }
  48. // std::cin.get();
  49. return 0;
  50. }