-1

I have a simple function of the form:

double f(double x)
{
...
}

For that function, I want to use data from a txt file, which I pass to an array:

ifstream inFile;

    inFile.open("data.txt");


    //Counting lines
    string s;
    int nlines=0;

    while(!inFile.eof()){
        getline(inFile, s);
        nlines++;
    }

    inFile.seekg(0, ios::beg);

    while(!inFile.eof()){
        inFile >> a[entry_data];
        inFile >> b[entry_data++]; 
    }

    inFile.close();

If I put this code inside the function f, each time the function is called, it will have to open the file, create the array... and so on. I want to avoid this by defining the array just the first time the function is called, or before. How can I do this?

I know that if I define the array in the main scope and pass it to the function as an argument I can solve this, but I want to keep the main scope as clean as possible. Thanks!

Psyphy
  • 25
  • 4

2 Answers2

0

Your f function takes 1 (one) value, not an array.

You want to use std::vector<double> instead of array, if you want to pass the data.

Your loop should be:

double value1, value2;
std::vector<double> a;
std::vector<double> b;
while (inFile >> value1 >> value2)
{
   a.push_back(value1);
   b.push_back(value2);
}

You can use your f function:

const size_t size = a.size();
for (size_t index = 0; index < size; ++size)
{
  double result = f(a[index]);
  //...
}

Edit 1: Function to Load
You could create an input function and call it once in main:

void input_data(std::istream& input, std::vector<double>& a, std::vector<double>& b)
{
  double value1, value2;
  while (input >> value1 >> value2)
  {
     a.push_back(value1);
     b.push_back(value2);
  }
}
Thomas Matthews
  • 52,985
  • 12
  • 85
  • 144
0

Let's create an instance that will read your data.

class DataHolder
{
    DataHolder()
    {
    ifstream inFile;

    inFile.open("data.txt");

    double v1, v2;

    while(inFile >> v1 >> v2){
        a.push_back(v1); 
        b.push_back(v2);
    }
    }
public:
    static DataHolder& getInstance()
    {
        static DataHolder d;
        return d;
    }
    std::vector<double> a, b;
};

Then in your function, use the data holder:

double f(double x)
{
    auto& d = DataHolder::getInstance();
    // use the holders data
}
Matthieu Brucher
  • 19,950
  • 6
  • 30
  • 49