Reputation: 21
I'm trying to make a the contents. However, I'm having quite a bit of trouble with ifstreamI'm probably lacking knowledge as I'm quite new to coding, but I'd appreciate any help
Upvotes: 1
Views: 917
Reputation: 944
It isn't really clear what you're asking here.
With regards to passing an instance of std::ifstream
as an argument, it may be because you aren't using references correctly.
Notice the reference operator (&
) next to the file_stream
argument. This will prevent the errors I expect you're seeing, that might look like this without it:
use of deleted function ‘std::basic_ifstream<_CharT, _Traits>::basic_ifstream(const std::basic_ifstream<_CharT, _Traits>&) [with _CharT = char; _Traits = std::char_traits]’ file_reader.printFile(file_reader.file_stream);
This error is happening because you're trying to copy the stream instance. Passing-by-reference means the function will use the same instance of the stream, not a copy of it.
Here's an example of what your program might look like. I've used your approach of handing the class its own members to operate on (in this case, file_stream
), but this is an odd way of doing it. Perhaps read up a little more on how classes work.
#include <iostream>
#include <string>
#include <fstream>
class FileRead {
public:
std::ifstream file_stream;
FileRead(const std::string &file_name) {
file_stream = std::ifstream(file_name);
}
static void printFile(std::ifstream &file_stream) {
std::string word;
while(file_stream >> word)
std::cout << word << std::endl;
}
};
int main() {
FileRead file_read("A:\\Coding\\Hobbit.txt");
file_read.printFile(file_read.file_stream);
}
Upvotes: 2