Search code examples
c++functionvariablesifstream

Accessing three different variables form one file in three different functions in C++


I am really new in C++. I have a file containing three columns of data e.g. a1 a2 a3. Now I want to ifstream the value of a1, a2, and a3 in three different functions. like

    ifstream input("file.txt"); 
    input >> a1;
    input >> a2;
    input >> a3;
   int Function1()
                {
                 Here I want to access a1
                }

   int Function2()
                {
                Here I want to access a2
                }
   int Function3()
                {
                Here I want to access a3
               }

How can I do that? Looking for kind help.


Solution

  • Pass them as parameters.
    For example:

    int Function1(int x) { return x + 1; }
    int Function2(int x) { return x + 2; }
    int Function3(int x) { return x + 3; }
    
    // ...
    
    int a1 = 0;
    int a2 = 0;
    int a3 = 0;
    ifstream input("file.txt"); 
    if (input >> a1 >> a2 >> a3)
    {
        cout << Function1(a1) + Function2(a2) - Function3(a3);
    }