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;
}

Mojtaba Ahmadi
  • 1,044
  • 19
  • 38
keyrimee
  • 11
  • 4
  • 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. – Mojtaba Ahmadi Nov 23 '20 at 22:34

1 Answers1

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

gsamaras
  • 71,951
  • 46
  • 188
  • 305