I would like my program to read a file using the function "readFile" below. I am trying to find out how to call a function with an istream& parameter. The goal of the function is to read the file by receiving the file's name as parameter.
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
bool readFile(std::istream& fileName); //error 1 this line
int main(void)
{
string fileName;
cout << "Enter the file name: ";
cin >> fileName;
readFile(fileName); //error 2 this line
}
bool readFile(std::istream& fileName)
{
ifstream file(fileName, ios::in); //error 3 this line
return true;
}
The three errors I get:
error 1 : in passing argument 1 of 'bool readFile(std::istream&)
error 2 : invalid initialization of reference of type 'std::istream& {aka std::basic_istream&}' from expression of type 'std::string {aka std::basic_string}
error 3 : invalid user-defined conversion from 'std::istream {aka std::basic_istream}' to 'const char*' [-fpermissive]
Is there anyway I can fix it? The parameter of the function really has to remain "std::istream& fileName".
Thanks for helping.
The first argument to the
std::ifstream
constructor should be a string. You're trying to pass it astd::istream
. Maybe thestd::istream
contains the name of the file you want to read, in which case you want to extract the name into astd::string
first. Something like this might work: