Search code examples
c++arraysfunctionuser-defined

C++ User defined function to populate an array


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


Solution

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