如何通过函数参数使用 fstream(特别是 ofstream)
How do I use fstream (specifically ofstream) through a functions parameters
嗨,我是一个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;
}
在这种情况下,您调用output
,out
作为参数。
既然你把自己描述为乞丐,我会相应地回答,希望以教育的方式。以下是正在发生的事情:将fstream
、ofstream
和ifstream
视为智能变量类型(即使您知道类是什么,为了逻辑清晰起见,也可以这样想)。像任何其他变量一样,您必须在使用之前声明它。声明后,该变量可以保存兼容的值。fstream
变量类型用于保存文件。它的所有变体都持有相同的东西,只是它们所做的是不同的。
使用该变量打开文件,在程序中使用它,然后关闭。
希望这有帮助
相关文章:
- 我刚刚安装了Visual Studio,遇到了一些错误,特别是WindowsSDKDir属性未定义.可能找不到某些生成工
- 平均循环值(特别是 HSL 配色方案中的色调)
- 如何通过函数参数使用 fstream(特别是 ofstream)
- 使用 C/C++ 以外的语言构建共享库,特别是 prolog
- 是否提供了在linux上交叉编译gtkmm(特别是v3)windows库/应用程序的说明
- GCC 地址清理器 - 将库功能列入黑名单(特别是 boost::test)
- std::bind通常适用于仅移动类型,特别是std::unique_ptr
- 当我可以将RNG传递给分发时,为什么要使用variate_generator?(特别是C++和Boost)
- 了解函数特征模板的工作原理.特别是,指向成员函数的指针是怎么处理的
- 如何在C++中使用%d,特别是在DrawText()中
- 如何在SWIG包装C++代码中向目标语言(特别是Python)添加替代构造函数
- 如何将c合并到c中(特别是lex)
- C++-占位符是如何工作的(特别是在boost::type_erasure中)
- 如何在xml树中反向行走节点,特别是libxml/c++
- 当您泄漏"device"和"device context"时会发生什么 - 特别是 d3d?
- 转换到另一个库(特别是c++)
- 我迷失在提升库中(特别是boost_program_options)
- msys/MinGW,即使安装了也找不到libpng,试图编译xpdf(特别是pdftopng)
- 并发与并行——特别是在c++中
- 矢量化/优化循环,用于宽寄存器(特别是Xeon Phi)的未对齐数据访问