Welcom to RO_wsy's blog

一个运用map的文本转换程序

本程序的功能是对文本中需要转换的单词进行转换。

程序需要两个文件,一个文件存放转换单词对照表,另一个文件存放要进行转换的文本。

本程序的文本文件内容如下:

trans_word_map.txt

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

to_be_trans.txt

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

程序设计和思路在程序注释中有说明,不再赘述

代码如下:

/*
*	单词转换程序
*	命令后带两个参数
*		第一个参数表示对照表
*		第二个参数表示待转换文件
*/
#include <iostream>
using namespace std;
#include <map>
#include <sstream>
#include <fstream>
#include <string>
#include <exception>

int main(int argc, char** argv)
{
	//trans_map用来存放对照表信息
	//key是原文单词,value是转换后单词
	map<string, string> trans_map;
	string key, value;

	//判断命令格式是否合法
	if (argc != 3)
		throw "wrong number of agruments";

	//打开对照表文件
	ifstream map_file(argv[1]);
	//判断打开成功与否
	if (!map_file)
		throw "no transformation file";

	//将文件内容读入trans_map
	while(map_file >> key >> value)
		trans_map.insert(make_pair(key, value));

	//打开待转换文件
	ifstream input(argv[2]);
	//判断打开成功与否
	if(!input)
		throw "no input file";

	string line;
	bool firstword;//判断是否是第一个单词,用来控制输出

	//将文件内容读入并进行转换输出
	while (getline(input, line)){
		stringstream is(line);
		string word;
		is >> word;
		firstword = true;
		while(is >> word){
			//返回相应word的迭代器
			map<string, string>::const_iterator map_it = trans_map.find(word);
			if(map_it != trans_map.end())
				//进行转换
				word = map_it->second;

			//输出控制
			if(firstword)
				firstword = false;
			else
				cout << ' ';
			cout << word;
		}
		cout << endl;
	}

	return 0;
}


 输入结果如下:

posted @ 2012-06-27 11:11  RO_wsy  阅读(236)  评论(0编辑  收藏  举报