Hey, I'm trying to read an istream into a file, but I'm getting the error that I invalidly tried converting std::istream to const char* . Here's the part of main() that mentions it:
1 2 3 4 5 6 7 8 9 10 11 12
//int main()
//...
case 2: {
ifstream ifs(argv[1]);
if (!ifs) {
cerr << progname << ": couldn't open " << argv[1] << endl;
return 1;
}
eventList.fill(ifs);
break;
}
//...
And here's the function outside of main() that mentions it:
1 2 3 4 5 6 7 8 9 10 11 12
void EventList::fill(istream& is)
{
std::string line;
ifstream myFile(is);
if (myFile.is_open())
{
while (getline(myFile,line))
eventListPQ.push(atoi(line));
myFile.close();
}
else cout << "Cannot open file.\n";
}
I understand that I have an istream in fill() and a char* in main(), I just wanna know how I could make it work. And I can't change anything in main() by the way, it's pre-written by my professor.
I'm not sure exactly what you are trying to do. The ifstream constructor expects a string as argument but you are passing a stream object.
If you want the fill function to read from the same file as is why not simply use is inside fill without creating myFile?
If is contains a filename of a file that you want myFile to read from you will have to extract the filename into a string first, possibly by using getline.
Yeah but you call fill no matter if the file could be opened or not.
You can check is the same way you check ifs.
Just some thoughts... The fill function receives a istream object so should it really assume it's a file? I mean if fill expects to read from a file why not make is a ifstream&?
In my opinion if the fill function accepts a istream& it should not assume it's a file stream. It could just as well be std::cin or some other input stream object. So in other words it shouldn't assume the stream can be opened or closed. I think it's the responsibility of whoever calls the fill function (main() in this case) to make sure the file is opened and closed correctly. Calling close() is not totally necessary because the file will be closed automatically in the ifstream destructor.