function with an istream& parameter C++

2019-02-16 03:01发布

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.

1条回答
We Are One
2楼-- · 2019-02-16 03:19

The first argument to the std::ifstream constructor should be a string. You're trying to pass it a std::istream. Maybe the std::istream contains the name of the file you want to read, in which case you want to extract the name into a std::string first. Something like this might work:

std::string fileName;
name >> fileName;
std::ifstream file(fileName, ios::in);
查看更多
登录 后发表回答