/*
文本转换程序,将一个输入的txt文件中的某些单词根据已知的转换表转换成对应的单词
说明:1.map_file.txt中存放的是单词的转换表,也就是一个单词对应一个单词,放在程序的同目录下
2.trans.txt中存放的是需要转换的文本
3.该程序使用的是map容器实现
*/
#include <iostream>
#include <map>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
//编写打开文件用于读
ifstream& open_file(ifstream &in,const string file)
{
in.close();
in.clear();
//读文件
in.open(file.c_str());
return in;
}
int main()
{
string key,value;
map<string,string> trans_map;
//打开文件是否成功进检查
ifstream infile;
if(!open_file(infile,"map_file.txt"))
{
throw runtime_error("file can not open");
return -1;
}
else
{
//将转换表(文本)读入到map中
while(infile >> key >> value)
{
trans_map.insert(make_pair(key,value));
}
}
//输入要转换的文本
ifstream input;
if(!open_file(input,"trans.txt"))
{
throw runtime_error("file can not open");
return -1;
}
else
{
map<string,string>::iterator it;
string line,word;
while(getline(input,line))
{//每次读取一行字符
//定义string输入流,每次只读入一个string
istringstream stream(line);
//标记每一行第一个单词第一个单词前不用输出空格
bool firstword = true;
while(stream >> word)
{
it = trans_map.find(word);
//如果输出的是第一个单词则不用输出空格
if(firstword)
{
firstword = false;
}
else
{
cout << " ";
}
//对应转换单词
if(it != trans_map.end())
{
cout << it->second;
}
}
cout << endl;
}
}
return 0;
}
C++中map容器实现单词转换的程序
最新推荐文章于 2021-02-04 19:56:06 发布