c++ 单词转换 map对象
2015-07-02 17:01
495 查看
#include <map> #include <sstream> #include <fstream> #include <iostream> #include <string> #include <exception> using namespace std; ifstream& openfile(ifstream &in,const string &filename){ in.close();//close in case it was alrady open in.clear();//clear any existing errors in.open(filename.c_str());//open the file we were given //in要么于指定文件绑定起来了,要么处于错误条件状态 return in;//condition state is good if open succeeded } int main(int argc,char** argv) { map<string,string> trans_map; string key,value; ifstream map_file; if(!openfile(map_file,"transform.txt")){ throw runtime_error("no transformation file"); } //read the tansformation map and build the map while(map_file>>key>>value){ trans_map.insert(pair<string,string>(key,value)); } ifstream input; if(!openfile(input,"source.txt")){ throw runtime_error("no input file"); } string line;//hold each line from the input //read the text to transform it a line at a time while(getline(input,line)){ istringstream stream(line); //read the line a word at a time string word; //读字符串流 bool lineFirst=true;//controls whether a space is printed while(stream>>word){ //ok:the actual mapwork,this part is the heart of the program map<string,string>::const_iterator iter=trans_map.find(word); if(iter!=trans_map.end()){ //replace it by the transformation value in the map word=iter->second; } if(lineFirst){ cout<<word; lineFirst=false; }else{ cout<<" "<<word;//print space between words; } } cout<<endl;//done with this line of input } return 0; }
transform.txt文件内容:
em them
cuz because
gratz grateful
i I
nah no
pos supposed
sez said
tanx thanks
wuz was
source.txt文件内容:
nah i sez tanx cuz i wuz pos to
not cuz i wuz gratz
程序运行输出:
相关文章推荐
- C/C++ 获取文件中有效行的数量
- C/C++相对论——C++中为什么要使用异常?
- 用指向指针的指针的方法对字符串和整数排序
- vc++读写ini文件
- c++复习
- 编译frostwire项目jlibtorrent_jni.cpp
- c++ 哪些自定义的数据类型
- C++ 怎么获得当前操作系统的语言,是英文版本还是简体或繁体
- C++中cout和cerr的区别?
- C++中class和struct的区别
- 浅谈树链剖分(C++、算法、树结构)
- C++字符串操作二
- 类中的构造函数与析构函数、函数重载以及this指针的总结
- C/C++ 快速排序 quickSort
- c++正则表达式日期格式匹配
- C++:STL标准入门汇总
- C语言中关于进程的函数
- 【C语言学习】《C Primer Plus》第10章 数组和指针
- C++ 操作法重载
- 从String类看写C++ class需要注意的地方