c++ text formatting
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double num = 123.456;
// Formatting output
cout << fixed << setprecision(2) << "Formatted number: " << num << endl;
return 0;
}
Explanation:
- #include <iostream>
: Includes the input/output stream library for basic I/O operations.
- #include <iomanip>
: Includes the input/output manipulator library for formatting output.
- using namespace std;
: Allows using elements from the standard C++ library without prefixing them with std::
.
- int main() {...}
: The main function where the program execution begins.
- double num = 123.456;
: Declares and initializes a variable num
of type double
with the value 123.456
.
- cout << fixed << setprecision(2) << "Formatted number: " << num << endl;
:
- cout
: Standard output stream used to display the output.
- fixed
: Manipulator used to display floating-point numbers in fixed-point notation.
- setprecision(2)
: Sets the precision of the output to 2 decimal places.
- "Formatted number: "
: Text displayed before the value of num
.
- num
: The value of the variable num
.
- endl
: Manipulator used to insert a newline and flush the output buffer.
- return 0;
: Indicates successful termination of the main()
function.