0

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
BeepBop
  • 3
  • 2
  • possible duplicate of [C/C++: Array size at run time w/o dynamic allocation is allowed?](http://stackoverflow.com/questions/737240/c-c-array-size-at-run-time-w-o-dynamic-allocation-is-allowed) – Cory Kramer Feb 09 '15 at 12:25
  • You're printing out the values, so you can base your assumption on that rather than on the sum. What is the input, output expected output (including the printed out values). – stefaanv Feb 09 '15 at 12:25
  • You cannot size your array `x` with the variable `p`. The size needs to be known at compile time, not runtime (barring certain compiler extensions) – Cory Kramer Feb 09 '15 at 12:25

1 Answers1

4

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.

Community
  • 1
  • 1
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455