#include <iostream>
#include<string>
#include<fstream>//文件操作头文件
using namespace std;
int main()
{
string s1="line 1",s3;
string s2="line 2",s4;
//-------------------
ofstream f1("1.txt",ios::out);//写文件句柄
f1<<s1<<endl;
f1<<s2<<endl;
f1.close();
//-----------------
ifstream f2("1.txt",ios::in);//读文件句柄
// f2>>s3;
//f2>>s4;读文件时这样读到空格就会停止
getline(f2,s3);//读一行,可包含空格
getline(f2,s4);
f2.close();
cout<<s3<<endl;
cout<<s4<<endl;
return 0;
}
读取文件内容
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
string s;
ifstream f("main.cpp",ios::in);//没有等号
while(!f.eof()))//注意判断文件尾的方式
{
getline(f,s);
cout<<s<<endl;
//if(f.eof())
//break;
}
return 0;
}
查找英汉词典
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class Dict
{
private:
ifstream f;
string word,s,s1;
public:
Dict()
{
f.open("英汉词典.txt",ios::in);
}
void find_w()
{
int n;
cout<<"input a word:" ;
cin>>word;
string s2;
while(true)
{
getline(f,s);
s2=s;
n=s.find(" ",0);
s1=s.substr(0,n);//从零开始取,取n位
if(s1==word)
{
cout<<s2<<endl;
break;
}
if(f.eof())
{
cout<<"no word"<<endl;
break;
}
}
}
~Dict()
{
f.close();
}
};
int main()
{
Dict d;
d.find_w();
return 0;
}