C++读写文件,查找英汉词典(注意英汉词典文件要放在程序文件夹下)

#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;
}

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值