福建农林大学金山学院实验报告
系(教研室):________ 专业:计算机科学与技术年级: _________________
实验课程:面向对象程序设计姓名: ______ 学号:__________ 实验室号__________
计算机号___________ 实验时间:_____________ 指导教师签字:____________ 成绩:_____________
实验9 C++的I/O流
一、实验目的和要求
(1)掌握一般类型数据的输入输出格式控制方法。
⑵掌握重载“ << ”和“ >> ”的方法。
(3)掌握对文件的输入输出操作方法。
二、实验内容和原理
1、编程实现下面要求:打印有符号数和无符号数200;以数据符号左对齐、数据本身右对齐方式输
出整数9999,域宽为15;将十进制整数300以0x开头的十六进制格式输出;用前导符号$格式打印9.876,域宽为&
2、定义一个分数类fraction ,通过重载运算符“ <<”以分数形式输出分数的结果,如将三分之二输出为2/3。
3、编写一个程序来统计文件file.txt 中的某个特定英文字符的个数。
(如:用户输入“ a”,则统计出该文件中出现“ a ”的次数)。
三、实验环境
1.硬件:PC机;
2.软件:Windows操作系统、Visual C++ 6.0
四、算法描述及实验步骤
1.
(1)在VC环境下根据题目写出类
(2)检查程序有无错误(包括语法错误和逻辑错误),有则改之。
(3)编译和连接。
#in clude<iostream>
#in clude<ioma nip>
using n amespace std;
int mai n()
{cout<<"打印无符号数和有符号数200"<<endl;
int x=200;
cout<<setw(6)<<x;
cout.setf(ios::showpos);
cout<<setw(6)<<x<<e ndl;
cout<<"以数据符号左对齐、数据本身右对齐方式输出整数9999,域宽为15"<<endl;
cout.setf(ios::internal);
cout.width(15);
cout<<9999<<endl;
cout<<"将十进制整数300以Ox开头的十六进制格式输出"<<endl;
cout.setf(ios::showbase);
cout<<hex<<300<<endl;
cout<<" 用前导符号$格式打印9.876 ,域宽为8。
"<<endl; cout.setf(ios::right); cout.fill('$');
cout.unsetf(ios::showpos);
cout<<setw(8)<<9.876<<endl;
return 0;
}
(4)运行程序,,分析结果。
2.
(1)在VC环境下根据题目写出类
( 2)检查程序有无错误( 包括语法错误和逻辑错误) ,有则改之。
( 3)编译和连接。
#include<iostream.h>
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)
{os<<fr.den<<'/'<<fr.num;
return os;
}
int main()
{Fraction fenshu(2,3);
cout<<" 三分之二="<<fenshu<<endl;
return 0;
}
( 4)运行程序,,分析结果。
3.
(1)在vc环境下根据题目写出类
(2)检查程序有无错误(包括语法错误和逻辑错误),有则改之。
(3)编译和连接。
#in clude<iostream>
#in clude<fstream>
using n amespace std;
int mai n()
{int coun t=0;
ifstream in file("file.txt");
if(!i nfile)
{cout <<"File cannot be ope ned."<<e ndl;
return 0;
}
while(!i nfile.eof())
{char N;
N=i nfile.get();
if(N=='a')
{co un t=co un t+1;}
}
cout<<"文件有:"<<count<<"个a"<<endl;
in file.close();
return 0;
}
(4)运行程序,,分析结果。
五、调试过程
---------------------- Configuration: 9-1 - Min32 D Coniiiling ___
9.1k cpp
9.1 -obj error(s) , t* warning(s)
1
.
____________ ConFiguration: 9.2 - ltin32 Conpiling
9.2.cpp
9 .2 _obi - 0 errorf s ), O uiarninq(s)
2.
---------------------- C onfIguratJDn: 9.3 - \ Conpilimg ・.*
9-3_cpp
9.3.obj ~ 9 error(s). 0 uarning(s)
六、实验结果
■I Xi^kKumentsandSettingsVJ^智嘛面渤建文件夹⑵VJebug怪l,exe T
打印无符号数和有符号数翻国
200 +200
以数据符号左对齐、数据本身右对齐方式输出整数汕跖•域宽为站+ 9?99
将十进制整数刑0以血开头的十六进制格式输出
0xi2c
用前导符号$格式打印筑域宽为仇
$$$9.876
Press an9 key to continue
1.
Pocum^rts and Settings^智桌面潇建文件夹Q匪t
吕分之二弘
2.
Press an9 kev to continue
3.测试用的file.txt 中写有bbbbbbbbbacccccccca
ClOocimeno snc 5亡ttingJ小召莫面新逹文件夹-2'1;T 序件有’小
Press an^ key to 匚on t in Lie
七、总结
1.掌握了一般类型数据的输入输出格式控制方法。
2.掌握了重载“ << ”和“ >> ”的方法。
3. 了解了打开关闭文件的方法,懂得了文件流的一些操作。