- 2
- 0
- 约1.92千字
- 约 4页
- 2019-09-10 发布于山西
- 举报
福建农林大学金山学院实验报告
系(教研室):信息与机电工程系 专业: 计算机科学与技术 年级: 2009
实验课程: 面向对象程序设计 姓名: 学号: 实验室号 612
计算机号 实验时间: 指导教师签字: 成绩:
实验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、
#includeiomanip
using namespace std;
int main()
{
cout.setf(ios::left);
cout.width(15);
cout以数据符号左对齐、数据本身右对齐方式输出整数9999,域宽为15endl;
cout9999endl;
cout.setf(ios::right);
cout打印有符号数和无符号数200endl;
int x=200;
coutsetw(6)x;
cout.setf(ios::showpos);
coutsetw(6)xendl;
cout将十进制整数300以0x开头的十六进制格式输出endl;
cout.setf(ios::showpos);
couthexxendl;
cout用前导符号$格式打印9.876,域宽为8endl;
cout.fill($);
cout.unsetf(ios::showpos);
coutsetw(10)9.876endl;
return 0;
}
2、
#includeiostream
using namespace std;
class Fraction
{
public:
Fraction(int x=0,int y=1);
friend ostream operator(ostream,Fraction);
private:
int den;
int num;
};
Fraction::Fraction(int x,int y)
{
den=x;
num=y;
}
ostream operator(ostream os,Fraction fr)
{
osfr.den/fr.num;
return os;
}
int main()
{
Fraction fenshu(2,3);
cout分数:fenshuendl;
return 0;
}
3、
#includeiostream
#includefstream
using namespace std;
int main()
{
int
count=0;
streampos start,end;
ifstream infile(file.txt);
if(!infile)
{
coutfile cannot be opened.endl;
return 0;
}
char s;
cout请输入要查找的字符endl;
cins;
while(!infile.eof())
{
If
(
s==infile.get()
)
count=count+1;
}
cout文件有count个字符endl;
infile.close();
return 0;
}
五、调试过程
1、
2、
3、
六、实验结果
1、
2、
3、
七、总结
(1)体会格式化输入输出的应用;
(2)学会文本文件的读写;
(3)能够通过编译时出现的出错提示信息,进行初步的纠错。
原创力文档

文档评论(0)