如何通过函数参数使用 fstream(特别是 ofstream)

How do I use fstream (specifically ofstream) through a functions parameters

本文关键字:特别是 ofstream fstream 何通过 函数 参数      更新时间:2023-10-16

嗨,我是一个c++初学者,这是我的任务之一,我有点卡住了。这不是我的全部代码,它只是我需要帮助的片段。我正在尝试做的是有一个函数专用于将该函数的所有内容导出到称为 results.txt 的text文件中。因此,当我打开文件时,应该显示"执行此操作"行,但是当我运行文件时,我收到诸如

">

错误 C2065:"输出":未声明的标识符">

"错误 C2275: 'std::ofstream' : 非法使用此类型作为表达式">

"智能感知:不允许使用类型名称">

">

智能感知:标识符"out"未定义">

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

using namespace std;
//prototypes
void output(ofstream& out);
int main()
{
output(ofstream& out);
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
return 0;
}
void output(ofstream& out)
{
out << "does this work?" << endl;
}

现在真的晚了,我只是在空白我做错了什么。

首先,这很好:

void output(ofstream& out)
{
out << "does this work?" << endl;
}

但是,这不是:

int main()
{
output(ofstream& out); // what is out?
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
return 0;
}

这是您收到的第一个错误:"错误 C2065:'out':未声明的标识符",因为编译器还不知道 out。

在第二个片段中,您希望使用特定ostream&调用输出。您不是调用函数,而是提供函数声明,这在此上下文中是不允许的。您必须使用给定的ostream&调用它:

int main()
{
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
output(out); // note the missing ostream&
return 0;
}

在这种情况下,您调用outputout作为参数。

既然你把自己描述为乞丐,我会相应地回答,希望以教育的方式。以下是正在发生的事情:将fstreamofstreamifstream视为智能变量类型(即使您知道类是什么,为了逻辑清晰起见,也可以这样想)。像任何其他变量一样,您必须在使用之前声明它。声明后,该变量可以保存兼容的值fstream变量类型用于保存文件。它的所有变体都持有相同的东西,只是它们所做的是不同的。

使用该变量打开文件,在程序中使用它,然后关闭

希望这有帮助