1. 实验目的和要求
(1) 理解I/ O流与标准流对象的意义,掌握文件的基本操作
(2) 掌握常用的IO 成员函数:正确打开关闭文件,检测流状态并进行顺序读写操作。
(3) 了解文件的随机读写方法,理解二进制文件与文本文件的区别
2. 实验内容:
1、 建立用户自定义复数类Complex,类中包括private整数数据成员real和imaginary,重载流插入和流读取运算符实现输入输出操作。
1)必须按标准格式输入,如(3,-8)、(-4,0)。判断输入的数据是否合法,如果是非法数据或者格式不匹配,则指示输入不正确。
2)按照标准格式进行输出,如3-8i、-4和5i, 当实部或者虚部为0时不显示0,虚部为负时不显示加号“+”。
3)编写函数main进行测试,从键盘输入10个Complex对象,将其写入文件中;从文件中读取最后一个数据,将其输出到屏幕上。
#include<iostream>
#include<stdlib.h>
#include<fstream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex() {}
Complex(int r,int i):real(r),imag(i) {}
~Complex() {}
friend ostream& operator <<(ostream& out, Complex& c);
friend istream& operator >>(istream& in, Complex& c);
};
ostream& operator <<(ostream& out, Complex& c)
{
if(c.real==0)
out<<c.imag<<'i'<<endl;
else if(c.imag>0)
out<<c.real<<'+'<<c.imag<<'i'<<endl;
else if(c.imag==0)
out<<c.real<<endl;
else
out<<c.real<<c.imag<<'i'<<endl;
return out;
}
istream& operator >>(istream& in, Complex& c)
{
char a,b,d;
cout<<"Input a complex (x,y):"<<endl;
while(1)
{
in>>a>>c.real>>b>>c.imag>>d;
if(a=='('&&b==','&&d==')'&&(int)c.real==c.real&&(int)c.imag==c.imag)//按标注格式输入
return in;
else
{
cerr<<"Input Error"<<endl;
cout<<"Please input a right complex (x,y):"<<endl;
}
}
}
int main()
{
Complex c[10];
ofstream outFile("F:\\complex.txt");
if(!outFile)
{
cerr<<"Fail to open the file"<<endl;
exit(0);
}
for(int i=0; i<3; i++)
{
cin>>c[i];
outFile<<c[i];
}
outFile.close();
ifstream inFile("F:\\complex.txt");
if(!inFile)
cerr<<"Fail to open the file"<<endl;
char buffer[256];
inFile.seekg(11,ios::beg);//等价于inFile.seekg(location)
while(!inFile.eof())//读取文件中所有字符串
{
inFile.getline(buffer,5);//???
//从文件中读取换行以前的字符,最多读取5个
cout<<buffer<<endl;
}
return 0;
}
2、某个文件中存储了一段英文文字,每个单词由空格、逗号、句号和换行符分割。统计某个文本文件中包含单词的个数和单词的平均长度。
#inclu