学习使用map容器
可以理解为:一种映射,一对一(例如x对y),可以通过x查询到唯一对应的y。
读取电子词典的文件,一对一压入map容器中(即英文对应中文解释),
然后通过英文,获得中文含义,以达到电子词典的功能。
1、打开电子词典的text文本文件;
2、使用按行读取文件中的内容(文件中一行,代表一个单词以及中文解释);
3、将读取到的数据通过sscanf函数进行拆分(通过空格判断拆分),将英文与中文分开,一对一存入map容器中
4、循环执行2、3步,直到读到文件末尾结束;
5、输入单词,使用map容器的函数去查询得到中文解释。
实现代码
#include <iostream> using namespace std; //#define _CRT_SECURE_NO_WARNINGS #pragma warning (disable:4996)//用来屏蔽sscanf的警告 #include <map> #include <fstream> int main() { map<string, string> wordDict; fstream fs; fs.open("dict.txt", ios::in); char buf[1024] = { 0 }; char key[200] = { 0 }; char value[200] = { 0 }; while (fs.peek() != EOF) { fs.getline(buf, 1024); sscanf(buf, "%s %s", key, value); wordDict.insert(pair<string, string>(key, value)); } cout << wordDict.size() << endl; string word; while (1) { cout << "请输入要查询的单词:" << endl; cin >> word; int res = wordDict.count(word); if (res == 0) { cout << "未查询到该单词!" << endl; } else { cout << "单词说明如下:" << endl; cout << wordDict[word] << endl; } } return 0; }
电子词典的文件截图:
运行结果: