带有 istream& 参数的 C++ 函数

标签 c++ istream

<分区>

我希望我的程序使用下面的“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”。

感谢您的帮助。

最佳答案

您需要决定是要传递字符串还是文件名。如果你传递一个字符串,那么调用者需要传递这个字符串,并且函数需要写成期望一个文件名。

如果您决定传递一个流,调用者需要打开并传递该流,并且需要编写该函数以期望它只使用一个流。

选项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;
}

选项 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;
}

任何一个都可以工作——你只需要在调用者和被调用者之间保持一致。根据强烈偏好,您还希望在整个给定代码库中尽可能保持一致。

关于带有 istream& 参数的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21505329/

相关文章:

c++ - 公共(public)私钥生成(openssl,evp,EC)中的编译器错误

c++ - 如何检查 std::cin 是否与终端或管道关联

c++ - 如何使用 ATL/WTL 制作您自己的类原生(可复制)控件?

c++ - 列表 <string> 的编译器错误

python - 从 python 传递到 C++ 的数组中未映射的内存访问

c++ - std::istream 提取设置 failbit 没有明显原因

c++ - 如何检查cin中是否有任何东西[C++]

C++ 中的 Java ToString 方法

c++ - istream::tellg() 在与我的自定义 streambuf 类一起使用时返回 -1?

c++ - 从 C++ 中的 istream 对象读取时如何检测空行?