Search code examples
c++arraysfstream

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. 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.


Solution

  • 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.

    Not to mention the fact that runtime-sized arrays are not standard C++; some compilers (such as GCC) support them as an extension, but it's best not to rely on them.

    When you need a dynamically-sized array in C++, use 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.

    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.