需要的东西
1.一个词典的txt文件
2.创建map容器
map<string, string> find; //map容器<string类型,string类型> 变量名
map容器
底层:二叉树,查找速度非常快
有两个值,一个是key值(唯一), 一个value是数据、
3.代码实现过程
1、打开电子词典的text文本文件;
2、使用按行读取文件中的内容(文件中一行,代表一个单词以及中文解释);
3、将读取到的数据通过sscanf函数进行拆分(通过空格判断拆分),将英文与中文分开,一对一存入map容器中
4、循环执行2、3步,直到读到文件末尾结束;
5、输入单词,使用map容器的函数去查询得到中文解释。
头文件
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
#include <fstream>
#include <map>
#pragma warning(disable:4996)
main
int main()
{
//创建map容器
map<string, string> find;
//fstream通常表示文件流,且同时具有 ofstream 和 ifstream 两种功能,
//这意味着它可以创建文件,向文件写入信息,从文件读取信息。
fstream fs;
//打开文件:dict.txt
fs.open("dict.txt", ios::in | ios::out);
char buf[1024] = {0};
char key[200] = {0};
char value[200] = {0};
//peek查看下一个字符,EOF表示文件末尾
while (fs.peek() != EOF)
{
//getline从文件中读取一行数据
fs.getline(buf, 1024);
//这里实现拆分,%s空格%s分别存入key, value
sscanf(buf, " %s %s", key, value);
//map变量 insert存入数据
find.insert(pair<string, string>(key, value));
}
//存入数据个数
cout << find.size() << endl;
string word;
while (1)
{
cout << "请输入单词" << endl;
cin >> word;
int res = find.count(word);
if (res == 0)
{
cout << "单词不存在" << endl;
}
else
{
cout << find[word] << endl;
}
}
return 0;
}