您的位置:首页 > 其它

第十四周阅读程序2

2015-06-10 08:50 183 查看
例11:

代码:

#include<iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
int main( )
{
int a[10];
ofstream outfile("f1.dat",ios::out);//定义文件流对象,打开磁盘文件"f1.dat"
if(!outfile)                        //如果打开失败,outfile返回0值
{
cerr<<"open error!"<<endl;
exit(1);
}
cout<<"enter 10 integer numbers:"<<endl;
for(int i=0; i<10; i++) //向磁盘文件"f1.dat"输出数据
{
cin>>a[i];
outfile<<a[i]<<" ";
}
cout<<"The numbers have been writen to file. "<<endl;
outfile.close();       //关闭磁盘文件"f1.dat"
return 0;
}


运行结果:



例12:

代码:

#include<iostream>
#include <fstream>
#include<cstdlib>
using namespace std;
int main( )
{
int a[10],max,i,order;
ifstream infile("f1.dat",ios::in);
//定义输入文件流对象,以输入方式打开磁盘文件f1.dat
if(!infile)
{
cerr<<"open error!"<<endl;
exit(1);
}
for(i=0; i<10; i++)
{
infile>>a[i];  //从磁盘文件读入10个整数,顺序存放在a数组中
cout<<a[i]<<" ";
}          //在显示器上顺序显示10个数
cout<<endl;
max=a[0];
order=0;
for(i=1; i<10; i++)
if(a[i]>max)
{
max=a[i];                //将当前最大值放在max中
order=i;                 //将当前最大值的元素序号放在order中
}
cout<<"max="<<max<<endl<<"order="<<order<<endl;
infile.close();
return 0;
}


运行结果:



例13:

代码:

#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
void save_to_file( );
void get_from_file();
int main( )
{
save_to_file( );
//调用save_to_file( ),从键盘读入一行字符并将其中的字母存入磁盘文件f2.dat
get_from_file( );
//调用get_from_file(),从f2.dat读入字母字符,改为大写字母,再存入f3.dat
return 0;
}

// save_to_file函数从键盘读入一行字符,并将其中的字母存入磁盘文件
void save_to_file( )
{
ofstream outfile("f2.dat");
//定义输出文件流对象outfile,以输出方式打开磁盘文件f2.dat
if(!outfile)
{
cerr<<"open f2.dat error!"<<endl;
exit(1);
}
char c[80];
cin.getline(c,80);		   //从键盘读入一行字符
for(int i=0; c[i]!=0; i++) //对字符逐个处理,直到遇′/0′为止
if((c[i]>=65 && c[i]<=90)||(c[i]>=97 && c[i]<=122))//如果是字母字符
{
outfile.put(c[i]);       //将字母字符存入磁盘文件f2.dat
cout<<c[i];
}                            //同时送显示器显示
cout<<endl;
outfile.close();                 //关闭f2.dat
}

//从磁盘文件f2.dat读入字母字符,将其中的小写字母改为大写字母,再存入f3.dat
void get_from_file()
{
char ch;
ifstream infile("f2.dat",ios::in);
//定义输入文件流outfile,以输入方式打开磁盘文件f2.dat
if(!infile)
{
cerr<<"open f2.dat error!"<<endl;
exit(1);
}
ofstream outfile("f3.dat");
//定义输出文件流outfile,以输出方式打开磁盘文件f3.dat
if(!outfile)
{
cerr<<"open f3.dat error!"<<endl;
exit(1);
}
while(infile.get(ch))//当读取字符成功时执行下面的复合语句
{
if(ch>=97 && ch<=122)          //判断ch是否为小写字母
ch=ch-32;                  //将小写字母变为大写字母
outfile.put(ch);               //将该大写字母存入磁盘文件f3.dat
cout<<ch;                      //同时在显示器输出
}
cout<<endl;
infile.close( );                 //关闭磁盘文件f2.dat
outfile.close();                 //关闭磁盘文件f3.dat
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: