c++学习笔记——个单词转换的map程序详解

实现功能:给定一个string,将它转换为另一个string。程序输入是两个文件,第一个文件保存转换规则,第二个文件为将要进行转换的文本。

IDE:Windows7+VS2013

#include "stdafx.h"
#include <map>
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <sstream>
using namespace std;

map<string, string> buildMap(ifstream &map_file)     //读入给定rules.text文件,建立转换映射
{
	map<string, string> trans_map;   //保存转换规则
	string key;						 //要转换的单词
	string value;					//替换后的内容
	//读取第一个单词存入key中,行中剩余内容存入value
	while (map_file >> key && getline(map_file, value))
		if (value.size() > 1)        //检查是否有转换规则
			trans_map[key] = value.substr(1); 
		else
			throw runtime_error("no rule for " + key);
	return trans_map;
}
const string &transform(const string &s, const map<string, string> &m)
{
	auto map_it = m.find(s);

	if (map_it != m.cend())        //如果单词在转换规则m中
		return map_it->second;     //使用替换短语
	else
		return s;                  //否则返回原string
}
void word_transform(ifstream &map_file, ifstream &input)
{
	auto trans_map = buildMap(map_file);   //保存转换规则
	cout << "转换规则为: \n";
	for (auto entry : trans_map)
		cout << "key: " << entry.first<< "\tvalue: " << entry.second << endl;
	cout << "\n\n";
	string text;                     //保存输入中的每一行
	cout << "转换后为: \n";
	while (getline(input, text))
	{  
		istringstream stream(text); //读取每一个单词
		string word;
		bool firstword = true;     //控制是否打印空格
		while (stream >> word) 
		{
			if (firstword)
				firstword = false;
			else
				cout << " ";  
			cout << transform(word, trans_map); 
		}
		cout << endl;        
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	if (argc != 3)
		throw runtime_error("wrong number of arguments");
	ifstream map_file(argv[1]);    //第一个参数为rules.text文件
	if (!map_file)             
		throw runtime_error("no transformation file");
	ifstream input(argv[2]);      //第二个参数为text.text文件
	if (!input)                 
		throw runtime_error("no input file");
	word_transform(map_file, input); 
	return 0;  
}

将rules.text和text.text文件放在E盘根目录下


设置运行时参数,在项目属性里面,配置属性->调试->命令参数里面写上你的参数


调试运行,结果如图示




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值