利用map存放单词及汉字解释,map存储在文件中,程序运行时将文件中信息读入到 map中。支持: (1)单词查阅,输入英文,输出中文。 (2)可添加新单词;添加结果要写入到文件中。添加单词如果已存在,则修改信息。 (3)可删除单词。删除后的单词表写入文件中。
时间: 2024-01-22 19:20:00 浏览: 34
以下是一个简单的实现,使用了C++11的新特性,如auto和range-based for循环:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <map>
using namespace std;
const string dictFile = "dictionary.txt";
// 从文件中读入字典
void loadDict(map<string, string>& dict) {
ifstream fin(dictFile);
if (!fin.is_open()) {
cerr << "Error: unable to open file " << dictFile << endl;
return;
}
string word, meaning;
while (fin >> word >> meaning) {
dict[word] = meaning;
}
fin.close();
}
// 将字典写入文件
void saveDict(const map<string, string>& dict) {
ofstream fout(dictFile);
if (!fout.is_open()) {
cerr << "Error: unable to create file " << dictFile << endl;
return;
}
for (const auto& p : dict) {
fout << p.first << " " << p.second << endl;
}
fout.close();
}
// 查找单词
void lookupWord(const map<string, string>& dict) {
string word;
cout << "Enter word to lookup: ";
cin >> word;
auto it = dict.find(word);
if (it == dict.end()) {
cout << "Not found." << endl;
} else {
cout << it->first << ": " << it->second << endl;
}
}
// 添加或修改单词
void addOrUpdateWord(map<string, string>& dict) {
string word, meaning;
cout << "Enter word to add/update: ";
cin >> word;
cout << "Enter meaning: ";
cin >> meaning;
dict[word] = meaning;
saveDict(dict);
}
// 删除单词
void deleteWord(map<string, string>& dict) {
string word;
cout << "Enter word to delete: ";
cin >> word;
auto it = dict.find(word);
if (it == dict.end()) {
cout << "Not found." << endl;
} else {
dict.erase(it);
saveDict(dict);
}
}
int main() {
map<string, string> dict;
loadDict(dict);
int choice;
do {
cout << "1. Lookup word" << endl;
cout << "2. Add/update word" << endl;
cout << "3. Delete word" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice (1-4): ";
cin >> choice;
switch (choice) {
case 1:
lookupWord(dict);
break;
case 2:
addOrUpdateWord(dict);
break;
case 3:
deleteWord(dict);
break;
case 4:
break;
default:
cout << "Invalid choice." << endl;
break;
}
} while (choice != 4);
return 0;
}
```
这个程序使用了一个名为“dictionary.txt”的文件来存储字典内容,每行一个单词和它的汉字解释,中间用空格隔开。在程序启动时,会从这个文件中读入字典,并将其存储在一个map对象中。每次添加、修改或删除单词后,程序都会将map对象写回到文件中。