如何让键盘输入字符保存在.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:
N
Here are the current contents of the D:\guests.txtfile:
Enter guest names:
RAOZIBIN
LUSHANSHAN
Here are the new contents of the D:\guests.txt file:
RAOZIBIN
LUSHANSHAN
Done!
请按任意键继续. . .
第二次运行结果:
Enter Y/N if you want to clear the D:\guests.txt file:
N
Here are the current contents of the D:\guests.txtfile:
RAOZIBIN
LUSHANSHAN
Enter guest names:
BEIJING
SHANGHAI
WUHAN
Here are the new contents of the D:\guests.txt file:
RAOZIBIN
LUSHANSHAN
BEIJING
SHANGHAI
WUHAN
Done!
请按任意键继续. . .