65,210
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Word_
{
friend istream& operator >> (istream &ris, Word_ &word); //重载输入操作
string english;
string chinese;
};
istream& operator >> (istream &ris, Word_ &word)
{
string strValue;
getline(ris, strValue); //read line
word.chinese.clear();
word.english.clear();
if (!strValue.empty())
{
string::size_type pos = strValue.find(" ||| ");
if (pos != string::npos)
{
word.chinese = strValue.substr(0, pos);
word.english = strValue.substr(pos + 5, strValue.size());
//要去除后面的空格
if (word.english.at(word.english.size() - 1) == ' ')
{
word.english = word.english.substr(0, word.english.size() - 1);
}
}
}
return ris;
}
void Print(const Word_ &word)
{
cout << word.chinese << "\t" << word.english << "\n";
}
Word_* Find(vector<Word_> &vecWord, string english)
{
if (vecWord.empty() || english.empty())
{
return NULL;
}
vector<Word_>::iterator iter;
vector<Word_>::iterator begin = vecWord.begin();
vector<Word_>::iterator end = vecWord.end();
for (iter = begin; iter != end; ++iter)
{
if (english == (*iter).english)
{
return &(*iter);
}
}
return NULL;
}
int _tmain(int argc, _TCHAR* argv[])
{
ifstream infile;
infile.open("D:\\test.txt");
if (!infile)
{
return 0;
}
vector<Word_> vecWord; //保存结构的容器
Word_ stword;
while (infile >> stword, !infile.eof()) //读文件
{
if (!stword.chinese.empty())
{
vecWord.push_back(stword);
}
}
//打印信息
for_each(vecWord.begin(), vecWord.end(), Print);
cout << "\n查找 :" ;
string english;
cin >> english;
//查找
Word_ *pword = Find(vecWord, english);
if (pword != NULL)
{
cout << "\n" << pword->chinese << "\t" << pword->english << endl;
}
return 0;
}