0

I'm just using cout to check if the function worked correctly. The cout that's in the function works and the output is 17 which is the first number in the text file. However, the cout in the main() function outputs 0. Why is this?

#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>

using namespace std;

double arrayPop();

int main()
{
    double X[10];
    double Y[10];

    arrayPop();

    cout<<Y[0];

    return 0;
}

double arrayPop()
{
    string horAxis, vertAxis;

    ifstream input;
    input.open("lin_reg-2.txt");

    input>>horAxis;
    double X[10];
    for (int i = 0; i<10; i++)
    {
        input>>X[i];
    }

    input>>vertAxis;
    double Y[10];
    for (int i = 0; i<10; i++)
    {
        input>>Y[i];
    }

    cout<<Y[0]<<endl;
}

1
  • Because in the main() function you declared some vectors with no initialization. There is no relation between the X and Y arrays in main() and arrayPop(). You should pass them by parameters with the function. Commented Nov 23, 2020 at 22:34

1 Answer 1

1

You need to pass your array as a parameter to the method arrayPop().

Then you would have something like this:

#include <iostream>
#include <fstream>

using namespace std;

void arrayPop(double X[], double Y[], const int size);

int main()
{
    const int size = 10;
    double X[size];
    double Y[size];

    arrayPop(X, Y, size);

    cout<<Y[0];

    return 0;
}

void arrayPop(double X[], double Y[], const int size)
{
    string horAxis, vertAxis;

    ifstream input;
    input.open("lin_reg-2.txt");

    input >> horAxis;
    for (int i = 0; i < size; i++)
    {
        input >> X[i];
    }

    input >> vertAxis;
    for (int i = 0; i < size; i++)
    {
        input >> Y[i];
    }

    cout<<Y[0]<<endl;
}

PS: I suggest you read about Variable Scope in C++.

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

2 Comments

This made so much sense and helped a lot. Thanks a bunch.
Hi keyrimee, if you think this answers your question, then you may consider to mark it as the accepted answer

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.