【问题标题】:Passing ifstream as parameter in functions在函数中将 ifstream 作为参数传递
【发布时间】:2021-01-18 20:36:20
【问题描述】:

我正在尝试制作内容。但是,我在使用 ifstream 时遇到了很多麻烦我可能缺乏知识,因为我对编码还很陌生,但我会很感激任何帮助

【问题讨论】:

  • 您在代码中的哪个位置尝试将 ifstream 作为参数传递?你到底得到了什么错误?
  • 如果我试图通过函数传递 ifstream,文件变量将不起作用,因为它不是同一类型。
  • 请编辑您的问题以显示您遇到问题的尝试以及确切的错误。我不知道你写的几个函数中的哪一个是“函数”,或者你是如何尝试将 ifstream 作为参数传递给它的。
  • 如果我将“string f”更改为“string & f”,我输入到函数中的主要字符串不再有效。
  • 最好的明确方法是提供不起作用的代码(最好是minimal reproducible example)以及带有问题的错误消息的确切文本。问题中较少的噪音几乎总是能提供更快更好的结果。更好的是,制作minimal reproducible example 通常会引导您找到解决方案。

标签: c++ function file parameter-passing ifstream


【解决方案1】:

这里不是很清楚你在问什么。

关于将std::ifstream 的实例作为参数传递,可能是因为您没有正确使用引用。

请注意 file_stream 参数旁边的引用运算符 (&)。这将防止我期望您看到的错误,没有它可能看起来像这样:

使用已删除的函数'std::basic_ifstream<_chart _traits>::basic_ifstream(const std::basic_ifstream<_chart _traits>&) [with _CharT = char; _Traits = std::char_traits]’ file_reader.printFile(file_reader.file_stream);

发生此错误是因为您尝试复制流实例。通过引用传递意味着函数将使用流的相同实例,而不是它的副本。

这是您的程序可能看起来的示例。我已经使用了你的方法来处理类它自己的成员来操作(在这种情况下,file_stream),但是这一种奇怪的方法。或许阅读更多关于类如何工作的内容。

#include <iostream>
#include <string>
#include <fstream>

class FileRead {

public:

    std::ifstream file_stream;

    FileRead(const std::string &file_name) {
        file_stream = std::ifstream(file_name);
    }

    static void printFile(std::ifstream &file_stream) {
        std::string word;
        while(file_stream >> word)
            std::cout << word << std::endl;
    }

};

int main() {
    FileRead file_read("A:\\Coding\\Hobbit.txt");
    file_read.printFile(file_read.file_stream);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-13
    • 2023-04-02
    • 2011-02-13
    • 2013-08-25
    • 2016-02-16
    • 2013-10-30
    相关资源
    最近更新 更多