单词转换(map对象)

 

结果:

./trans file1 file2
no I said thanks because I was supposed to not because I was grateful

file1:

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

file2:

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

生成file1 and file2

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

ofstream & openFile(ofstream &out,const string &fileName)
{
	//open file
	out.close();
	out.clear();
	out.open(fileName.c_str());
	return out;
}

ofstream & write(ofstream &out)
{
	//write data to file1

	cout<<"Enter some key-values:"<<endl;
	string key,value;
	while(cin>>key>>value)
		out<<key<<'\t'<<value<<endl;
	return out;
}

ofstream & write(ofstream &out,int val)
{
	//val只是起到重载函数的作用
	//write data to file2

	cout<<"Enter some keys:"<<endl;
	string key;
	while(cin>>key)
		out<<key<<' ';
	return out;
}

int main()
{
	string fileName,fileName2;
	cout<<"Enter a file name:"<<endl;
	cin>>fileName;
	cin.clear();

	//write
	ofstream outFile;
	openFile(outFile,fileName);
	write(outFile);

	cin.clear();
	cout<<"Enter a file name again:"<<endl;
	cin>>fileName2;
	cin.clear();

	//write the second file
	ofstream outFile2;
	openFile(outFile2,fileName2);
	write(outFile2,2);  //2 重载函数


	return 0;
}

//单词转换
#include<iostream>
#include<map>
#include<string>
#include<fstream>
#include<sstream>
#include<stdexcept>
using namespace std;

ifstream & openFile(ifstream &in,const string &fileName)
{
	in.close();
	in.clear();
	in.open(fileName.c_str());
	return in;
}


int main(int argc,char *argv[])
{
	map<string,string> transMap;
	string key,value;

	if(argc!=3)
		throw runtime_error("wrong number of arguments!");

	//open file 
	ifstream mapFile;
	if(!openFile(mapFile,argv[1]))
		throw runtime_error("no transformation file!");

	while(mapFile>>key>>value)
		transMap.insert(make_pair(key,value));

	ifstream input;
	if(!openFile(input,argv[2]))
		throw runtime_error("no input file!");
	string line;
	while(getline(input,line))
	{
		istringstream stream(line);
		string word;
		bool firstWord=true;
		while(stream>>word)
		{
			map<string,string>::const_iterator mapIt=transMap.find(word);
			if(mapIt!=transMap.end())
				word=mapIt->second;
			if(firstWord)
				firstWord=false;
			else
				cout<<" ";

			cout<<word;
		}
		cout<<endl;
	}

	return 0;
}

转载于:https://my.oschina.net/ppppower/blog/36779

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值