关于c++I/O流式程序

来源:百度知道 编辑:UC知道 时间:2024/06/06 07:07:45
void outputint(ofstream &ofs)
{
int a;
ofs.open("test.txt",ios_base::in);
while((a=cin.get())!=EOF)
{
ofs.write((char*)(&a),sizeof(int));
}
}
main()
{
outputint(ofs);
.....
}main中报错为invalid initialization of non-const reference of type 'std::ofstream&' from a temporary of type 'std::ofstream (*)()'
函数报错为 in passing argument 1 of `void outputint(std::ofstream&)'

ofstream是输出用的,怎么能用ios_base::in打开

可能是程序其它地方有问题,比如main里面把ofs声明成指针类型了.
以下代码编译运行没问题

#include <iostream>
#include <fstream>
using namespace std;

void outputint(ofstream &ofs)
{
int a;
ofs.open("C:/1.txt",ios_base::out);
while((a=cin.get())!=EOF)
{
ofs.write((char*)(&a),sizeof(int));
}
}
main()
{
ofstream ofs;
outputint(ofs);
}

你是想往文件中写东西啊,所以ofs的打开方式应该为out,或者app啊...in指的是打开文件从文件中读取.