Formatting Stream Output - C++ Data Type

C++ examples for Data Type:float

Introduction

You can format data using stream manipulators.

The following table lists the most useful manipulators and streams constants.

function Description
std::setprecision(n) Sets the floating-point precision or the number of decimal places to n digits.
std::setw(n) Sets the output field width to n characters, but only for the next output data item.
std::setfill(ch) Sets the character to fill, default is a space.

The iostream header defines the following stream constants:

std::fixed Output floating-point data in fixed point notation.
std::scientific Output all subsequent floating-point data in scientific notation, which always includes an exponent and one digit before the decimal point.
std::defaultfloatRevert to the default floating-point data presentation.
std::dec All subsequent integer output is decimal.
std::hex All subsequent integer output is hexadecimal.
std::oct All subsequent integer output is octal.
std::showbaseOutputs the base prefix for hexadecimal and octal integer values. Inserting std::noshowbase in a stream will switch this off.
std::leftOutput is left-justified in the field.
std::right Output is right-justified in the field. This is the default.
std::internalCauses the fill character to be internal to an integer or floating-point output value.

Demo Code

#include <iostream>
#include <iomanip>
#include <cmath>                       // For square root function
using std::cout;//from  w  w w .  j  av a 2 s  . c o  m
using std::cin;
using std::sqrt;

int main()
{
  const double fish_factor {2.0/0.5};  // Area per unit length of fish
  const double inches_per_foot {12.0};
  const double pi {3.14159265};

  double fish_count {};                // Number of fish
  double fish_length {};               // Average length of fish

  cout << "Enter the number of fish you want to keep: ";

  cin >> fish_count;

  cout << "Enter the average fish length in inches: ";

  cin >> fish_length;
  fish_length /=inches_per_foot;      // Convert to feet

  double pond_area {fish_count * fish_length * fish_factor};

  double pond_diameter {2.0 * sqrt(pond_area/pi)};

  cout << "\nPond diameter required for " << fish_count << " fish is "
     << std::setprecision(2)                        // Output value is 8.7
     << pond_diameter << " feet.\n";
}

Result


Related Tutorials