0

I have a text file with three values.

2.5 7.6 -3

I am trying to output the values in another text file, with a decimal point of 5 places. I have done this before with cout, however I am having trouble implementing it to fout. Below is me trying to do it similar to cout.

ofstream fout("roots.txt");

fout << setprecision(5);
fout << "The equation " << setprecision(5) << a << "x^2 + " << setprecision(5) << b << "x + " << setprecision(5) << c << " has roots " << root1 << " and " << root2 << endl;
fout.close();

I expect the output in the text document to be

The equation 2.50000x^2 + 6.70000x + -3.00000 = 0 has roots 0.39078 and -3.07078.

Currently the output is: The equation 2.5x^2 + 7.6x + -3 has roots 0.35361 and -3.3936

  • Can you clarify your problem? What output do you get instead of what you expect? `std::setprecision` works with your `fout` the same way as it does for `std::cout`. – walnut Oct 12 '19 at 03:10
  • @uneven_mark So right now I am getting the output: "The equation 2.5x^2 + 7.6x + -3 has roots 0.35361 and -3.3936 –" , the goal is to have each value consist of 5 points after the decimal point, such as the output "2.50000x^2 + 6.70000x + -3.00000 = 0 has roots 0.39078 and -3.07078" – Shaheer Khan Oct 12 '19 at 03:14
  • 1
    @uneven_mark Sorry, I went ahead and added it. – Shaheer Khan Oct 12 '19 at 03:16
  • possible duplicate: [Set precision with fstream to output file - format double](https://stackoverflow.com/questions/35029233/set-precision-with-fstream-to-output-file-format-double) – walnut Oct 12 '19 at 03:21
  • @uneven_mark That was it! I added fixed and it did the output correctly. Thanks! – Shaheer Khan Oct 12 '19 at 03:21
  • Just to be sure: [This works exactly the same for `std::cout`.](https://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout) – walnut Oct 12 '19 at 03:23

0 Answers0