电子词典:输入单词,显示单词的汉语翻译
思路分析:1.定义一个map<word,中文翻译> 对象 的map对象
2.下载英汉翻译文档,一行一行读取文档内信息,单词和中文翻译
3.读文件:获取单词,中文翻译 fstream open, getline 一行一行读得到字符串用sscanf拆分
4.插入map容器
5.重复3,4的动作,直到文件内容全部读完,用peek()==EOF来判断
6.输入单词
7.到map容器中根据输入的单词(word)查找用find
8.输出中文翻译
9.重复6,7,8动作,可以设置一下,输入q退出
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include<map>
#include<fstream>
#include<stdio.h>
#include<string>
#include <cstdio>
#include<stdlib.h>
int main()
{
char str[100] = { 0 };
char str1[50] = { 0 };
char str2[50] = { 0 };
string tmp1;
string tmp2;
string eng;
//打开文件
fstream filestr;
filestr.open("./dict.txt", fstream::in );
//定义一个map类对象
map<string, string> dictmap;
map<string, string>::iterator it;
while (filestr.peek()!=EOF)
{
filestr.getline(str, 100);
sscanf(str, "%s %s", str1, str2);
tmp1 = str1;
tmp2 = str2;
dictmap.insert(pair<string, string>(tmp1,tmp2));
}
cout << "文件中的字符数:" << dictmap.size() << endl;
while (1)
{
cout << "请输入英文:" ;
cin >> eng;
//c_str():将string类型转换为char
//if (strcmp(eng.c_str(), "q") == 0)
//{
// break;
//}
//类对象可以直接比较
if (eng == "q")
{
break;
}
it = dictmap.find(eng);
if (it == dictmap.end())
{
cout << "未找到" << endl;
}
else
{
cout << "汉语:" << it->second << endl;
}
}
//关闭文件
filestr.close();
return 0;
}