Kevin Nguyen
Kevin Nguyen

Reputation: 3

How do I open a file in main and then read from the file in another function?

In my main function I want to open a txt file while not hard-coding the file name, then call another function to read from the txt file.

I've tried to pass it as an argument according to another question thread, but it's solutions don't seem to work for me. The thread I looked at.

Sorry if this is an obvious question, I'm quite new to this so more in depth explanations are welcome.

Here's the code

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int readfile(double &a, double &b, double &c, ifstream filein)
{
    filein >> a >> b >> c;
    cout << a << b << c;
}

int main()
{
    double a, b, c;
    bool loop;
    

    string infilename;
    cout << "Enter the input filename to open\n";
    cin >> infilename;


    ifstream filein;
    

    filein.open(infilename);
   

    if (!filein)
    {
        cout << "Input file could not be opened";
        return 1;
    }
    else
    {
        loop = true;

    }
    


    while (loop == true )
    {
        readfile(a, b, c, filein);
    }
}

Here's the error message I'm getting stackoverflow.cpp|42|error: use of deleted function 'std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const std::basic_ifstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]'|

Upvotes: 0

Views: 68

Answers (1)

user17732522
user17732522

Reputation: 76678

An std::ifstream object cannot be copied, so you cannot pass it by-copy to a function expecting it by-value.

But you can pass it by-reference without any problem:

int readfile(double &a, double &b, double &c, ifstream &filein)

As mentioned by @RemyLebeau in the comments, it is also preferable to take a std::istream& instead of a std::ifstream& as parameter, since all standard input streams including std::ifstream inherit from std::istream and so you could have a function that takes a reference to any input stream, not just a file input stream.

Upvotes: 3

Related Questions