您的位置:首页 > 编程语言 > C语言/C++

单词转换(map对象)

2011-12-08 00:00 344 查看
结果:

./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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息