[英]Extracting double values from file into array
I am trying to extract double values from 2 different text files and will be putting them in arrays. 我试图从2个不同的文本文件中提取双精度值,并将其放入数组中。 Here is a snippet of the code: 这是代码片段:
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int p;
cout<<"Enter number of ordered pairs: ";
cin>>p;
cout<<endl;
double x[p];
ifstream myfile("x.txt");
while (myfile.good())
{
myfile>>x[p];
cout<<x[p]<<endl;
}
double testx = x[4]+x[3]+x[2]+x[1]+x[0];
cout<<endl<<"The sum of the values of x are: "<<testx<<endl<<endl;
double y[p];
ifstream myfile2("y.txt");
while (myfile2.good())
{
myfile2>>y[p];
cout<<y[p]<<endl;
}
double testy = y[4]+y[3]+y[2]+y[1]+y[0];
cout<<endl<<"The sum of the values of y are: "<<testy<<endl<<endl; system("PAUSE");
return EXIT_SUCCESS;
}
I don't think that the values are being stored properly since checking it via testx
and texty
, the sum of the values are not the expected ones. 我不认为这些值已正确存储,因为通过testx
和texty
对其进行了检查,这些值的总和不是预期值。
You're writing out of bounds of the arrays: you're writing into x[p]
and y[p]
, where x
and y
are arrays of size p
and thus valid indices are from 0
to p-1
. 您正在写出数组的边界:您正在写到x[p]
和y[p]
,其中x
和y
是大小为p
数组,因此有效索引是从0
到p-1
。
Not to mention the fact that runtime-sized arrays are not standard C++; 更不用说运行时大小的数组不是标准C ++了。 some compilers (such as GCC) support them as an extension, but it's best not to rely on them. 一些编译器(例如GCC)将它们作为扩展来支持,但是最好不要依赖它们。
When you need a dynamically-sized array in C++, use std::vector
: 当您需要C ++中的动态大小的数组时,请使用std::vector
:
int p;
cout<<"Enter number of ordered pairs: ";
cin>>p;
cout<<endl;
std::vector<double> x;
ifstream myfile("x.txt");
double d;
while (myfile >> d)
{
x.push_back(d);
cout<<b.back()<<endl;
}
DTTO for y
. DTTO为y
。
Note that I changed the loop condition—you were not testing the result of the input operation. 请注意,我更改了循环条件-您未测试输入操作的结果。 More info . 更多信息 。
Additionally, if the numbers are arbitrary floating-point values, remember they cannot be simply compared for equality in many situations, due to rounding errors and representation imprecisions. 此外,如果数字是任意浮点值,请记住,由于舍入误差和表示不精确,在许多情况下不能简单地比较它们的相等性 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.