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.

3
  • possible duplicate of C/C++: Array size at run time w/o dynamic allocation is allowed? Commented Feb 9, 2015 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). Commented Feb 9, 2015 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) Commented Feb 9, 2015 at 12:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.