将文件中的双精度值提取到数组中

Extracting double values from file into array

我正在尝试从 2 个不同的文本文件中提取双精度值并将它们放入数组中。这是代码片段:

#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;
}

我认为这些值没有正确存储,因为通过 testxtexty 检查它,值的总和不是预期的值。

您正在写出数组的边界:您正在写入 x[p]y[p],其中 xy 是大小为 p 因此有效索引是从 0p-1.

更不用说运行时大小的数组不是标准的 C++;一些编译器(如 GCC)支持它们作为扩展,但最好不要依赖它们。

当您在 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;
}

y.

的 DTTO

注意我改变了循环条件——你不是在测试输入操作的结果。 More info.

此外,如果数字是任意浮点值,请记住它们 cannot be simply compared for equality 在许多情况下,由于舍入误差和表示不精确。