文件的读写(fin && fout)
来源:互联网 发布:mac视频播放器加速 编辑:程序博客网 时间:2024/05/18 09:25
如何让键盘输入字符保存在.txt文件中
如何让我们自己在键盘上输入的字符不仅仅在屏幕上显示,而且还能保存在特定路径的文件中,这让简单枯燥的控制台命令程序变得略有趣。
首先,先看看cin和cout对象,cin和cout对象使得我们能够从键盘上获取字符,并在屏幕上显示出来。
cin对象的作用可以理解成实现:【键盘–>缓冲区】
如:string str; cin>>str;cout对象的作用可以理解成:【缓冲区–>屏幕上显示】
如:cout>>str;
该语句与上述语句实现,将字符串str中的内容送值屏幕上显示。
2.再看看fin和fout对象
fout对象的作用可以理解成:向文件中进行写操作 【从缓冲区–>硬盘】
fin对象的作用可以理解成:对文件中的内容进行读操作 【从硬盘–>缓冲区】
下面通过一小段代码进行测试:
#include "stdafx.h"#include <iostream>#include <fstream>#include <cstdlib>#include <string>#include <iomanip>using std::cin;using std::cout;using std::endl;using std::ifstream;using std::ofstream;using std::ios;using std::cerr;using std::string;using std::setw;const char *file="D:\\guests.txt";int _tmain(int argc, _TCHAR* argv[]){ char ch; cout<<"Enter Y/N if you want to clear the "<<file<<" file: "<<endl; if(cin.get()=='Y'){ ofstream fout; fout.open(file); fout.close(); } else{ cin.get(); // 获取当前输入流中的字符!!! ifstream fin; fin.open(file);//当前目录文件"guests.txt" if(fin.is_open()){ cout<<"Here are the current contents of the " <<file<<"file: "<<endl; while(fin.get(ch)) cout<<ch; fin.close(); } //add new names ofstream fout; fout.open(file,ios::out|ios::app);//ios::app格式实现在文件末尾进行追加内容 if(!fout.is_open()){ cerr<<"Can't open "<<file<<"file for output."<<endl; exit(EXIT_FAILURE); } cout<<"Enter guest names:"<<endl; string name; while(getline(cin,name) && name.size()>0){ fout<<name<<endl; //向文件中进行写操作 【从缓冲区-->硬盘】 } fout.close(); //Show revised file fin.clear(); fin.open(file); if(fin.is_open()){ cout<<"Here are the new contents of the " <<file<<" file: "<<endl; while(fin.get(ch)) cout<<ch; //对文件中的内容进行读操作 【从硬盘-->缓冲区】 fin.close(); } } cout<<endl<<"Done!"<<endl; return 0;}
运行示例图:
第一次运行结果:
Enter Y/N if you want to clear the D:\guests.txt file:NHere are the current contents of the D:\guests.txtfile:Enter guest names:RAOZIBINLUSHANSHANHere are the new contents of the D:\guests.txt file:RAOZIBINLUSHANSHANDone!请按任意键继续. . .
第二次运行结果:
Enter Y/N if you want to clear the D:\guests.txt file:NHere are the current contents of the D:\guests.txtfile:RAOZIBINLUSHANSHANEnter guest names:BEIJINGSHANGHAIWUHANHere are the new contents of the D:\guests.txt file:RAOZIBINLUSHANSHANBEIJINGSHANGHAIWUHANDone!请按任意键继续. . .
0 0
- 文件的读写(fin && fout)
- C++ 文件输入和输出fout fin
- OPNET中FIN,FOUT以及FRET的作用
- OPNET中FIN,FOUT以及FRET的作用
- TCP的FIN/RST Cookie
- 文件操作ofstream,open,close,ifstream,fin,按照行来读取数据, fstream,iosin iosout,fio.seekg(),文件写入和文件读写,文件拷贝和文件
- 串口的读写,文件读写
- INI文件的读写
- 读写文件的例子
- INI文件的读写
- 关于文件的读写
- 文件的读写操作
- 文件的读写操作
- properties文件的读写
- 读写服务器端的文件
- 位图文件的读写
- C++文件的读写
- ini文件的读写
- The method assertEquals(Object, Object) is ambiguous for the type Assert解决办法
- 在android里常用的默认开关的意义
- android传感器
- 第4周项目--程序阅读3对象是数组
- androidmanifest.xml权限中文说明
- 文件的读写(fin && fout)
- caffe 学习资料
- java内部类
- Python 字符串逆序
- VirtualBox的四种网络连接方式
- IntelliJ中的main函数和System.out.println()快捷键
- 一个牛人给初学者的建议
- KnockOutJs - Web版的WPF
- 浅谈Linux系统调用