读出istream对象cin中的回车换行符
程序员文章站
2022-05-26 11:29:44
...
file name:
boy
向磁盘文件中写入数据
beyonce
if i were a boy
love on top
The data in disk file is:
beyonce
if i were a boy
love on top
//文件名下多了一空行,令我百思不得其解。经研究发现cin中残存了回车换行符!
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
ofstream & openFile(ofstream &out,const string &fileName)
{
out.close();
out.clear();
out.open(fileName.c_str());
return out;
}
ifstream & openFile(ifstream &in,const string &fileName)
{
in.close();
in.clear();
in.open(fileName.c_str());
return in;
}
ofstream & write(ofstream &out)
{
//向磁盘文件中写入数据
cout<<"向磁盘文件中写入数据"<<endl;
string line,str;
//getline(cin,str); //读出cin中的回车换行符
while(getline(cin,line))
out<<line<<endl;
return out;
}
ifstream & read(ifstream &in)
{
//读取磁盘文件中的数据
cout<<"The data in disk file is:"<<endl;
string str;
while(getline(in,str))
cout<<str<<endl; //并输出到终端屏幕上
return in;
}
int main()
{
string fileName;
cout<<"file name:"<<endl;
cin>>fileName;
cin.clear();
//写文件
ofstream outFile;
openFile(outFile,fileName);
write(outFile);
//读文件
ifstream inFile;
openFile(inFile,fileName);
read(inFile);
inFile.close();
return 0;
}
//加上 getline(cin,str);就行了
转载于:https://my.oschina.net/ppppower/blog/35991
上一篇: 浅析数据结构之链表C/C++
下一篇: 数据结构第二章线性表