Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ output align and decimal place holder?

Tags:

c++

precision

Hi I got a little question here.
I am doing my C++ homework and the sample output is

% cat this.out
  5.00       0.00 
  1.55       4.76 
 -4.05       2.94 
 -4.05      -2.94 
  1.55      -4.76 

but what I got was

% cat test.out
    5       0
    1.55    4.76
    -4.05   2.94
    -4.05   -2.94
    1.55    -4.76

And I couldn't figure out how to make my output format looks like that. One more problem I had in this case is, I want the first line in my output is something like 5.00 0.00, but it doesn't work even I set precision(3)

Here is my code generates the output, please take a look.

file.open (filename, fstream :: in | fstream :: trunc);
    if(!file.is_open())
    {
            cerr << "Error opening file " << filename << endl;
            cout << "Exiting..." << endl;
            exit(0);
    }
    for(i = 0 ; i < num; i ++)
    {
            angle = 2 * M_PI * i/num;
            x = rad * cos(angle);
            y = rad * sin(angle);
            file.precision(3);
            // x, y are double
            file << "\t" << x << "\t" << y << endl;
    }
    cout << "finished";
    file.close();
like image 957
Allan Jiang Avatar asked Oct 16 '25 13:10

Allan Jiang


2 Answers

You need to look up the Input/output manipulators in the Standard library header <iomanip>.

These are used inline, like:

std::cout << "\t" << std::fixed << std::setprecision(z) << x

The ones you'll be most interested in are:

  • std::fixed
  • std::setprecision
  • std::setw
like image 119
Johnsyweb Avatar answered Oct 19 '25 02:10

Johnsyweb


This should do the trick:

file.precision(2);
file << fixed << "\t" << x << "\t" << y << endl;  
like image 21
AlexS Avatar answered Oct 19 '25 02:10

AlexS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!