如何通过函数参数使用fstream(特别是ofstream) [英] How do I use fstream (specifically ofstream) through a functions parameters
问题描述
您好,我是一个 c ++
初学者,这是我的任务之一,我有点卡住。这不是我的整个代码它只是一个我需要帮助的片段。我想做的是有一个函数专门用于导出一切与该函数到一个文本
文件,称为results.txt。因此,当我打开文件时,应该出现这个工作行,但当我运行该文件,我得到错误像
Hi I'm a c++
beginner and this is one of my assignments and I'm a bit stuck. This isn't my entire code it's just a snippet of what I need help with. What I'm trying to do is have one function dedicated to exporting everything with that function into a text
file which is called results.txt. So the line "does this work" should show up when I open the file, but when I run the file I get errors like
错误C2065:'out':未声明的标识符
"Error C2065: 'out' : undeclared identifier"
错误C2275:'std :: ofstream':非法使用此类型作为表达式
"Error C2275: 'std::ofstream' : illegal use of this type as an expression"
IntelliSense:类型名称不允许
"IntelliSense: type name is not allowed"
IntelliSense:标识符未定义
"IntelliSense: identifier "out" is undefined"
#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':未声明的标识符,因为编译器不知道。
This is the first error you get: "Error C2065: 'out' : undeclared identifier", because the compiler doesn't know about out yet.
在第二个片段中, code> ostream& 。不是调用函数,而是给出一个函数声明,在本上下文中不允许。你必须使用给定的 ostream&
来调用它:
In the second fragment you want to call output with a specific ostream&
. Instead of calling a function, you're giving a function declaration, which isn't allowed in this context. You have to call it with the given ostream&
:
int main()
{
ifstream in;
in.open("inven.txt");
ofstream out;
out.open("results.txt");
output(out); // note the missing ostream&
return 0;
}
在这种情况下,您可以 输出
与 out
作为参数。
In this case you call output
with out
as parameter.
这篇关于如何通过函数参数使用fstream(特别是ofstream)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!