zoukankan      html  css  js  c++  java
  • [STL]单词转换

    如果单词转换文件的内容是:

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

    而要转换的文本是:

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

    则程序将产生如下输出结果:

    代码如下:

     1 #include<iostream>
     2 #include<map>
     3 #include<string>
     4 #include<fstream>
     5 #include<sstream>
     6 using namespace std;
     7 
     8 int main()
     9 {
    10     map<string,string> trans_map;
    11     string key,value;
    12     ifstream ifile("a.txt");//a.txt存放转换文件
    13     if(!ifile) 
    14         throw runtime_error("no translation file");
    15     while(ifile>>key>>value)
    16     {
    17         trans_map.insert(make_pair(key,value));
    18     }
    19     ifstream input("b.txt");//b.txt存放要转换的文件
    20     if(!input)
    21         throw runtime_error("no input file");
    22     string line;
    23     while(getline(input,line))//每次读一行
    24     {
    25         istringstream stream(line);//每次读一个单词
    26         string word;
    27         bool firstword=true;//首个单词前不需要空格
    28         while(stream>>word)
    29         {
    30             map<string,string>::const_iterator map_it=trans_map.find(word);
    31             if(map_it!=trans_map.end())//若map中存在就替换
    32             {
    33                 word=map_it->second;
    34             }
    35             if(firstword)
    36             {
    37                 firstword=false;
    38             }
    39             else 
    40             {
    41                 cout<<" ";
    42             }
    43             cout<<word;
    44         }
    45         cout<<endl;
    46     }
    47     return 0;
    48 }
  • 相关阅读:
    java中的静态变量与实例变量
    Java中的关键字this
    继承和多类的基础(C++)
    11-1:(42)接雨水
    10-2
    10-1
    9-2
    9-1
    8-2
    8-1
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3371123.html
Copyright © 2011-2022 走看看