0

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]'|

1 Answers1

3

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.

user17732522
  • 53,019
  • 2
  • 56
  • 105
  • 1
    You should also get in the habit of passing I/O streams around by their base type. In this case, the parameter can use `istream&` and still work. But it makes the function more flexible should you ever want to read the same kind of data from a different type of stream in the future, such as `istringstream`, etc – Remy Lebeau Feb 02 '22 at 01:13