福建农林大学金山学院实验报告
系(教研室):信息与机电工程系专业:计算机科学与技术年级:2010级
实验课程:面向对象姓名:陈凯斯学号:100202053实验室号A605
计算机号J605s037 实验时间:2011/12/19 指导教师签字:成绩:
实验9 C++的I/O流
一、实验目的和要求
(1) 掌握一般类型数据的输入输出格式控制方法。
(2) 掌握重载“<<”和“>>”的方法。
(3) 掌握对文件的输入输出操作方法。
二、实验内容和原理
1、编程实现下面要求:打印有符号数和无符号数200;以数据符号左对齐、数据本身右对齐方式输出整数9999,域宽为15;将十进制整数300以0x开头的十六进制格式输出;用前导符号$格式打印9.876,域宽为8。
2、定义一个分数类fraction,通过重载运算符“<<”以分数形式输出分数的结果,如将三分之二输出为2/3。
3、编写一个程序来统计文件file.txt中的某个特定英文字符的个数。
(如:用户输入“a”,则统计出该文件中出现“a”的次数)。
三、实验环境
1. 硬件:PC机;
2. 软件:Windows操作系统、Visual C++ 6.0
四、算法描述及实验步骤
(1)#include<iostream.h>
int main()
{
int a=200,b=9999,c=300;
double d=9.876;
cout.setf(ios::showpos);
cout<<a<<endl;
cout.setf(ios::internal,ios::basefield);
cout.width(15);
cout<<b<<endl;
cout.setf(ios::showbase);
cout.setf(ios::hex);
cout<<300<<endl;
cout.width(8);
cout.fill('&');
cout.setf(ios::right,ios::basefield);
cout<<d;
return 0;
}
(2)
#include<iostream.h>
class fenshu
{
public:
fenshu(int a,int b){A=a;B=b;}
friend ostream& operator<<(ostream& s,fenshu& c)
{
s<<c.A<<"/"<<c.B;
return s;
}
private:
int A,B;
};
int main()
{
fenshu a(2,3);
cout<<a;
return 0;
}
(3)
#include<iostream.h>
#include<fstream.h>
int main()
{
char a;
int b=0;
ifstream infile("aaaa.txt");
if(!infile)cout<<"file could not open"<<endl; while(!infile.eof())
{
infile>>a;
if(a=='c')b++;
}
cout<<b<<endl;
infile.close();
return 0;
}
五、调试过程
六、实验结果
(1)
(2)
(3)
七、总结。