单词转换文件:
测试文件:
结果:
源代码:
#include<iostream>
#include<fstream>
#include<sstream>
#include<map>
using namespace std;
int main(void)
{
ifstream file; //单词对应
ifstream test; //测试用例
file.open("file.txt",ios::in);
test.open("test.txt",ios::in);
if(!file)
{
cout<<"file not found or file can't open"<<endl;
}
if(!test)
{
cout<<"test not found or test can't open"<<endl;
}
string key,value; //键值对
map<string,string> m; //map存贮
while(file>>key>>value)
{
m.insert(make_pair(key,value)); //存入map
}
string line;
string word;
bool isFirst;
map<string,string>::const_iterator it;
while(getline(test,line)) //每次读入一行
{
istringstream iss(line); //读取每个单词
isFirst=true;
while(iss>>word)
{
if((it=m.find(word))!=m.end()) //查找是否存在
{
word=it->second;
}
if(isFirst) //如果是第一个
{
isFirst=false;
}
else //如果不是第一个
{
cout<<' ';
}
cout<<word;
}
cout<<endl;
}
file.close();
test.close();
return 0;
}