1

I'm trying to read a bunch of constants of a text-file in C++ using the <fstream> library. The constants are 16 decimal places long, or 16 digits after the decimal point. Now, whenever I try to read those digits, the program truncates it to 6 decimal places whether I use the datatypes double or long double.

The program goes on something like this -

#include<iostream>
#include<fstream>
#include<vector>

using namespace std;

int main(){
    vector<double> test;
    ifstream fin;
    fin.open("constants.txt");
    double num;
    while(fin>>num){
        test.push_back(num);
    }
    for(int i=0; i<64; i++){
        cout<<test[i]<<"\n";
    }
    return 0;
}

And the constants, from the constants.txt file go on something like 0.2599210498948732, but when I try to print it using the program, it truncates it to 0.259921. What do i to print the entire of the 16 digit long decimal number?

  • 2
    The default output format uses just 6 decimal places. If you want more, you have to tell the I/O streams what to do. – Jonathan Leffler Sep 03 '21 at 16:33
  • 2
    `std::cout << std::setprecision(16) << test[i]` – perivesta Sep 03 '21 at 16:33
  • Does [How do I print a double value with full precision using cout?](https://stackoverflow.com/questions/554063/how-do-i-print-a-double-value-with-full-precision-using-cout) help you out? If yes, let us know and we'll mark the question as a duplicate. – user4581301 Sep 03 '21 at 16:35
  • Looks like setting the precision seems to be working. You can mark it as duplicate. thank you! – Pranav Desai Sep 03 '21 at 16:39

1 Answers1

1

Use std::cout.precision(). The limit precision of long double is 18.

long double number = 0.2599210498948732;
cout.precision(16);
cout << number;
  • Yes! Just learned that using `setprecision` on `long double ` is the solution to my problem. Thank you for the answer! – Pranav Desai Sep 03 '21 at 16:41