功能与istream&参数C ++ [英] function with an istream& parameter C++
问题描述
我希望我的程序使用下面的函数readFile来读取文件。我试图找出如何用istream& amp; amp;参数。该函数的目标是通过接收文件名作为参数来读取文件。
#include
#include< sstream>
#include< fstream>
#include< string>
使用namespace std;
bool readFile(std :: istream& fileName); //错误1 this line
int main(void)
{
string fileName;
cout<< 输入文件名称:;
cin>>文件名;
readFile(fileName); // error 2 this line
}
bool readFile(std :: istream& fileName)
{
ifstream file(fileName ,ios :: in); //错误3这行
返回true;
}
我得到的三个错误:
错误1:在传递'bool readFile(std :: istream&)的参数1中'
错误2:无效的类型为'std: :istream的&安培; {std :: basic_string}类型的表达式{aka std :: basic_istream&}'
错误3:无效的用户定义的从' std :: istream {aka std :: basic_istream}'到'const char *'[-fpermissive]
有反正我可以修复它吗?该函数的参数实际上必须保持std :: istream& fileName。
感谢您的帮助。
std :: istream
。也许 std :: istream
包含你想要读取的文件的名字,在这种情况下,你想把名字提取到 std ::字符串
首先。像这样的东西可能会工作: std :: string fileName;
名称>>文件名;
std :: ifstream文件(fileName,ios :: in);
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 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);
这篇关于功能与istream&参数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!