Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading double from file

For my homework I should read double values from a file and sort them. These are the some of the values. But when read them with my code, when a print it for testing they are written in integer form.

std::ifstream infile (in_File);
double a;
while(infile>>a)
{
    std::cout<<a<<std::endl;
}

My doubles are started with 185261.886524 then 237358.956723

And my code print the 185262 then 237359 then so on.

like image 472
Eren Söğüt Avatar asked Mar 18 '23 10:03

Eren Söğüt


2 Answers

Try adding this at the top of your main():

setlocale(LC_ALL, "C");

This will give your program the "C" locale instead of your local one. I imagine your local one uses "," as a decimal point instead of "." as in your data.

You will need to add #include <clocale> at the top of your file as well.

Edit: then, to get more precision, you can do #include <iomanip> and do this at the top of your program:

std::cout << std::setprecision(20);

setprecision changes how many total digits are printed.

like image 76
John Zwinck Avatar answered Mar 31 '23 16:03

John Zwinck


Your problem is not the input, but the output: cout by default prints 6 digits of a double, this is why you see the rounded value 185262, not 185261 as you would expect from incorrect input. Use std::setprecision to increase output precision.

like image 45
Baum mit Augen Avatar answered Mar 31 '23 16:03

Baum mit Augen