[英]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
我的双打是从185261.886524
然后237358.956723
开始的
And my code print the 185262
then 237359
then so on. 我的代码打印185262
然后237359
然后等等。
Try adding this at the top of your main()
: 尝试在main()
的顶部添加:
setlocale(LC_ALL, "C");
This will give your program the "C" locale instead of your local one. 这将为您的程序提供“C”语言环境而不是本地语言环境。 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. 您还需要在文件顶部添加#include <clocale>
。
Edit: then, to get more precision, you can do #include <iomanip>
and do this at the top of your program: 编辑:然后,为了获得更高的精度,您可以执行#include <iomanip>
并在程序的顶部执行此操作:
std::cout << std::setprecision(20);
setprecision
changes how many total digits are printed. setprecision
更改打印的总位数。
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. 你的问题不是输入,而是输出: cout
默认打印一个double
6位数字,这就是为什么你看到圆形值185262
,而不是185261
就像你对错误输入所期望的那样。 Use std::setprecision
to increase output precision. 使用std::setprecision
来提高输出精度。
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: 然后使用imbue
方法:
std::ifstream infile (in_File);
infile.imbue(std::locale("C"));
double a;
while(infile>>a)
{
std::cout<<a<<std::endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.