第十四周 阅读程序二
2015-06-09 19:20
375 查看
问题及代码:
例十一:
运行结果:
知识点总结:
例十二:
运行结果:
例十三:
运行结果:
例十一:
#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; }
运行结果:
知识点总结:
例十二:
#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; }
运行结果:
例十三:
#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 }
运行结果:
相关文章推荐
- Yii2 使用十七 国际化
- JDK各个版本的新特性jdk1.5-jdk8
- 20150526数据编码
- java.net.URISyntaxException的解决办法
- 如何进行Android客户端的优化?
- 软件文档知多少?
- 战天
- backtrack 使用Tab键补全命令
- Cpp Primer<<学习IO标准库--输出缓冲区的管理、文件输入与输出_6
- 升级IOS9,提示滑动升级,卡在密码锁屏界面,无反应了
- [Linux Shell]Access Windows Share Folder From Linux
- 如何写系统分析书
- 网络聚合CIDR配置OSPF、RIP路由重分发配置实例
- 20150525进制转换_Xcode
- Java学习篇之---Gson(Maven)
- 管家婆进销存7.2最完美的破解免安装版(已整合最新打印管理器)
- ubuntu下安装jdk
- android&Bluetooth
- 队列实现 java版本
- 防止VC调用chkstk函数