Eren Söğüt
Eren Söğüt

Reputation: 51

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.

Upvotes: 4

Views: 246

Answers (3)

Baum mit Augen
Baum mit Augen

Reputation: 50063

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.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249153

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.

Upvotes: 6

BartoszKP
BartoszKP

Reputation: 35891

This can happen if on your system your localization settings have a different decimal separator than .. Try add the following include:

#include <locale>

and then use the imbue method:

std::ifstream infile (in_File);
infile.imbue(std::locale("C"));
double a;
while(infile>>a)
{
    std::cout<<a<<std::endl;
}

Upvotes: 0

Related Questions