C++ Program to Demonstrate Use of Formatting Flags on Float Output

This C++ program demonstrates the use of formatting flags on float output. The formatting flags provided in the header ios_base helps to format the float output. The float output can be either in fixed, scientific or default format. The fixed format has fixed number of significant digits while the default one has the same number of significant digits as the original float value.

Here is the source code of the C++ program which demonstrates the use of formatting flags on float output. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate Use of Formatting Flags on Float Output
  3.  */
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.     float data;
  10.     ios_base::fmtflags old;    
  11.  
  12.     cout << "Enter a float value :\t";
  13.     cin >> data;
  14.     old = cout.flags();
  15.     cout.setf(ios_base::scientific, ios_base::floatfield);
  16.     cout << "\nScientific format :\t" << data << endl;
  17.     cout.setf(ios_base::fixed, ios_base::floatfield);
  18.     cout << "Fixed-point format :\t" << data << endl;
  19.     cout.setf(ios_base::fmtflags(0), ios_base::floatfield);
  20.     cout << "Default format :\t" << data << endl;
  21. }

$ a.out
Enter a float value :	12.3456
 
Scientific format :	1.234560e+01
Fixed-point format :	12.345600
Default format :	12.3456

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.