Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

A Quick Formatting Sample

To get you started, here's a quick sample that shows some of the formatting power in the C++ streams. Remember, a stream works the same, whether the stream is the console or a file. Therefore, I'll write the next several examples to the console and then later I'll show you a file example, and you'll see that they're the same.

Start up your favorite editor and type this in:

#include <iostream>
using namespace std;

int main() {
  int x = 100;
  int y = 20;
  int z = 5;
  
  float p = 3.1415;
  float q = 1.0 / 3.0;
  float r = 1;

  cout << "Take 1" << endl;  
  cout << x << " " << y << " " << z << endl;
  cout << p << " " << q << " " << r << endl;
  cout << endl;
  
  cout << "Take 2" << endl;
  cout.precision(3);
  cout << x << " " << y << " " << z << endl;
  cout << p << " " << q << " " << r << endl;
  cout << endl;
}

When you run this code, here's what you'll see on the console:

Take 1
100 20 5
3.1415 0.333333 1

Take 2
100 20 5
3.14 0.333 1

This output isn't bad, although it could stand for some improvements. But you can see what I did in the code: I used the precision function to set the floating-point precision to three significant digits. Now if you remember your high school chemistry class (that's usually where they harp on significant digits the most!) or if you're in chemistry class right now, you know that the number 0.333 has three significant digits. The 0 at the beginning doesn't count. As for the claim that 1 has three significant digits, well, most people might argue against that. But the C++ Standard Library treats 1 as having a single significant digit, with no way to convert it to three significant digits, thereby leaving it simply as 1.

Now you might notice something odd about the code, in particular this line:

cout.precision(3);

Most people think of cout as receiving text through the << operator. But cout is itself an object (that is, an instance of a class), and you can actually call its member functions. The precision function is one of its member functions. And this example calls precision, passing the number 3.

  • + Share This
  • 🔖 Save To Your Account