C++单词转换程序

给定一个string,将它转换成另一个string。程序的输入是两个txt文件,第一个文件保存转换规则(如下WordMap.txt),用来转换第二个文件中的文本(如下InFile.txt)。WordMap.txt中每一行是一条转换规则,每条转换规则由两部分组成:一个单词和一个用来替换它的语句。要求:根据WordMap.txt中的转换规则,转换InFile.txt的内容,并将转换内容保存到output.txt文件中。

// WordMap.txt

brb  be right back
k okay?
y why
r  are
u you
pic picture
thk thanks!
18r  later
hh   ^-^
bsw  best wishes!
// InFile.txt

where r u
y dont u send me a pic
k thk 18r
bsw hh

其程序如下:

// 单词转换程序

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

map<string, string> bulidMap(ifstream &map_file);
void word_transform(ifstream &map_file, ifstream &input, ofstream &outFile);

int main()
{
	cout << "main begin." << endl;
	
	string strfile1("WordMap.txt");
	string strfile2("InFile.txt");
	string strfile3("output.txt");

	ifstream mapFile(strfile1);
	ifstream inFile(strfile2);
	if (!mapFile.is_open() || !inFile.is_open())
	{
		cout << "Could not open the file named " << strfile1
			 << " or named " << strfile2 << "." << endl;
	}

	ofstream outfile(strfile3);
	if (outfile)
	{
		word_transform(mapFile, inFile, outfile);
	}

	mapFile.close();
	inFile.close();
	outfile.close();
	cout << "main end." << endl;
	return 0;
}

// 转换文本内容
void word_transform(ifstream &map_file, ifstream &input, ofstream &outFile)
{
	map<string, string> trans_map;
	try
	{
		trans_map = bulidMap(map_file);
	}
	catch(exception err)
	{
		cout << err.what() << endl;
		return;
	}
	

	string text;
	while (getline(input,text))
	{
		istringstream stream(text);
		string word;
		bool firstWord = false;

		while (stream >> word)
		{
			map<string, string>::iterator itor = trans_map.find(word);
			if (itor != trans_map.end())
			{
				outFile << itor->second;
			}
			else
			{
				outFile << word;
			}

			if (firstWord)
			{
				firstWord = false;
			}
			else
			{
				outFile << " ";
			}
		}

		outFile << endl;
	}

}

// 解析map文件
map<string, string> bulidMap(ifstream &map_file)
{
	map<string, string> trans_map;
	string key;
	string value;

	if (!map_file.is_open())
	{
		cout << "The map file is not open!" << endl;
		return map<string, string>();
	}

	while (map_file >> key && getline(map_file, value))
	{
		if (value.size() >= 1)
		{
			string::size_type pos = value.find_first_not_of(' ');
			if (pos != string::npos )
			{
				trans_map[key] = value.substr(pos);
			}
			else
			{
				throw runtime_error("no rule for key : " + key + ".");
			}
		}
		else
		{
			throw runtime_error("no rule for key : " + key + ".");
		}
	}
	
	return trans_map;
}


转换文本内容如下:

// outfile.txt

where are you 
why dont you send me a picture 
okay? thanks! later 
best wishes! ^-^ 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值