我希望我的程序使用下面的“readFile”函数读取文件。我试图找出如何使用 istream& 参数调用函数。该函数的目标是通过接收文件名作为参数来读取文件。
#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;
}
我得到的三个错误:
错误 1:传递 'bool readFile(std::istream&) 的参数 1
错误 2:从“std::string {aka std::basic_string}”类型的表达式对“std::istream& {aka std::basic_istream&}”类型的引用进行无效初始化
错误 3:从“std::istream {aka std::basic_istream}”到“const char*”的用户定义转换无效 [-fpermissive]
无论如何我可以修复它吗?该函数的参数确实必须保留“std::istream& fileName”。
谢谢你的帮助。
第一个论点std::ifstream
构造函数应该是一个字符串。你正试图通过它std::istream
。也许是std::istream
包含您要读取的文件的名称,在这种情况下您希望将该名称提取到std::string
第一的。像这样的事情可能会起作用:
std::string fileName;
name >> fileName;
std::ifstream file(fileName, ios::in);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)