c++ 单词转换 map对象

#include <map>
#include <sstream>
#include <fstream>
#include <iostream>
#include <string>
#include <exception>
using namespace std;

ifstream& openfile(ifstream &in,const string &filename){
	in.close();//close in case it was alrady open
	in.clear();//clear any existing errors
	in.open(filename.c_str());//open the file we were given
	//in要么于指定文件绑定起来了,要么处于错误条件状态
	return in;//condition state is good if open succeeded
}

int main(int argc,char** argv)
{
	map<string,string> trans_map;
	string key,value;
	ifstream map_file;
	if(!openfile(map_file,"transform.txt")){
		throw runtime_error("no transformation file");
	}
	//read the tansformation map and build the map
	while(map_file>>key>>value){
		trans_map.insert(pair<string,string>(key,value));
	}
	ifstream input;
	if(!openfile(input,"source.txt")){
		throw runtime_error("no input file");
	}
	string line;//hold each line from the input
	//read the text to transform it a line at a time
	while(getline(input,line)){
		istringstream stream(line); //read the line a word at a time
		string word;
		//读字符串流
		bool lineFirst=true;//controls whether a space is printed
		while(stream>>word){
			//ok:the actual mapwork,this part is the heart of the program
			map<string,string>::const_iterator iter=trans_map.find(word);
			if(iter!=trans_map.end()){ 
				//replace it by the transformation value in the map
				word=iter->second;
			}
			if(lineFirst){
				cout<<word;
				lineFirst=false;
			}else{
				cout<<" "<<word;//print space between words;
			}
		}
		cout<<endl;//done with this line of input
	}
	return 0;
}

transform.txt文件内容:

em them
cuz because
gratz grateful
i I
nah no
pos	supposed
sez said 
tanx thanks
wuz was

source.txt文件内容:

nah i sez tanx cuz i wuz pos to
not cuz i wuz gratz

程序运行输出:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值