单词转换(map对象)
2011-12-08 00:00
344 查看
结果:
file1:
file2:
生成file1 and file2
./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; }
相关文章推荐
- 10.3.9例子“单词转换”map对象
- C++ primer 单词转换 map对象
- 单词转换(map对象)
- C++ primer中,"单词转换"map对象源码问题
- C++ Primer 第十章 10.3.9 “单词转换”map对象
- C++ 10.3.9 "单词转换"map对象
- C++ primer ————————————“单词转换" map 对象
- C++ primer 单词转换(使用map对象)
- Java Object与Map对象相互转换
- 使用FastJson在JSON字符串、JSON对象及JavaBean、Map之间的相互转换
- 利用list和map代替对象模式,实现jdbc的简单操作,省去对象转换的繁琐步骤!
- 复杂json的转换 Map 数组 对象 生成 与 解析
- Java对象与Map的转换
- 把json对象串转换成map对象
- Map转换成Bean对象
- Java中把对象、对象bean、list集合、对象数组、Map和Set以及字符串转换成Json
- java如何将Bean对象转换成Map对象?
- java--09--对象、JSON、Map、XML之间的转换
- map与对象互相转换
- java中json包的使用以及字符串,map,list,自定义对象之间的相互转换