-1

I have a 2-dimensional array of doubles and I would like to output those numbers to a file (each second dimension is a line). That's not a problem. The problem is that the output numbers are saved in a txt file with different degree of precision. Example:

0       1.173   1.3     2.0744  0       0.13

But I would like them to be like:

0.0000  1.1730  1.3000  2.0744  0.0000  0.1300

I have tried std::setprecision(6) and std::cout.precision(6) but they don't seem to work on this, or maybe I use them in the wrong way. Here it is a simplified version of how I output data to a file:

std::ofstream ofile("document.dat");
for(int i = 0; i < array_size; i++) {
    ofile << array[i][0] << " " array[i][1] << std::endl;
}
Anselmo GPP
  • 425
  • 2
  • 21

2 Answers2

1

As comments have already noted, you want to use std::fixed (along with setting the width and precision), so you get something on this general order:

#include <iostream>
#include <iomanip>
#include <vector>

int main() {
    std::vector<std::vector<double>> numbers{
        {1.2, 2.34, 3.456},
        {4.567, 5, 6.78910}};

    for (auto const &row : numbers) {
        for (auto const &n : row) {
            std::cout << std::setw(15) << std::setprecision(5) << std::fixed << n << "\t";
        }
        std::cout << "\n";
    }
}

Result:

    1.20000         2.34000         3.45600 
    4.56700         5.00000         6.78910 
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
-2

multiply the float number with 10^n and store the value in an int variable to getrid of the decimals. Then divide the integer with 10^n and store it in a float then it is ready to be saved to a text file with a presicion of n decimal digits.

Kaan99__
  • 43
  • 1
  • 3