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.

有帮助吗?

解决方案

You need to decide whether you're going to pass a string, or a file name. If you pass a string, then the caller needs to pass the string, and the function needs to be written to expect a file name.

If you decide to pass a stream, the caller needs to open and pass the stream, and the function needs to be written expecting a stream that it'll just use.

option A:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;

bool readFile(std::string const &fileName);

int main(void)
{   
    string fileName;

    cout << "Enter the file name: ";
    cin >> fileName;

    readFile(fileName);
}

bool readFile(std::string const &fileName)
{
    ifstream file(fileName);
    return true;
}

Option B:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;

bool readFile(std::istream& file);

int main(void)
{   
    string fileName;

    cout << "Enter the file name: ";
    cin >> fileName;

    ifstream file(fileName);
    readFile(file);
}

bool readFile(std::istream& fileName)
{
    return true;
}

Either one can work -- you just need to be consistent between the caller and callee. By strong preference, you want to be as consistent as possible throughout a given code base as well.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top