将double值从文件提取到数组中

时间:2015-02-09 12:20:37

标签: c++ arrays fstream

我正在尝试从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进行检查,值无法正确存储,因此值的总和不是预期值。

1 个答案:

答案 0 :(得分:4)

您正在编写超出数组的范围:您正在写入x[p]y[p],其中xy是大小为{{1}的数组因此有效索引从p0

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

如果在C ++中需要动态大小的数组,请使用p-1

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。

请注意,我更改了循环条件 - 您没有测试输入操作的结果。 More info

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

相关问题