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

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

"Error C2065: 'out' : undeclared identifier"

"Error C2275: 'std::ofstream' : illegal use of this type as an expression"

"IntelliSense: type name is not allowed"

"IntelliSense: identifier "out" is undefined"

#include

#include

#include

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;

}

Right now it's really late and I'm just blanking out on what I'm doing wrong.

解决方案

First of all, this is fine:

void output(ofstream& out)

{

out << "does this work?" << endl;

}

However, this is not:

int main()

{

output(ofstream& out); // what is out?

ifstream in;

in.open("inven.txt");

ofstream out;

out.open("results.txt");

return 0;

}

This is the first error you get: "Error C2065: 'out' : undeclared identifier", because the compiler doesn't know about out yet.

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;

}

In this case you call output with out as parameter.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值