11.3.6 一个单词转换的map

// Demo.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>

transferMap build_map(const vector<string> &origin, const vector<string> &newword) {
   transferMap m;
   for (size_t i = 0; i < origin.size(); ++i) {
      m.insert(make_pair(origin[i], newword[i]));
   }
   return m;
}

string transfer(const transferMap m, string &s) {
   string t;
   transferMap::const_iterator itr = m.find(s);
   if (itr != m.cend()) {
      return itr->second;
   }
   return s;
}

void word_transfer(ifstream &f1, ifstream &f2) {
   string key, value;
   vector<string> origin;
   vector<string> newword;
   while (f1 >> key && getline(f1, value)) {
      origin.push_back(key);
      newword.push_back(value);
   }
   transferMap m = build_map(origin, newword);
   string line;
   while (f2 >> line) {
      cout << transfer(m, line) << " ";
   }
}

int main()
{
   ifstream f1("rule.txt"), f2("sample.txt");
   if (f1 && f2) {
      word_transfer(f1, f2);
   }

   return 0;
}

需要注意getline()的用法:http://www.cplusplus.com/reference/string/string/getline/

istream& getline (istream&  is, string& str);

以及字符串replace的用法:http://www.cplusplus.com/reference/string/string/replace/

string& replace (size_t pos,        size_t len,        const string& str);

我的程序中,将input的文本中的所有内容,按照都是单个的单词读取,因此输出不好看。
书本上给出了标准的程序:

string text;
while (getline(f2, text)) {
	istringstream stream(text);
	string word;
	bool firstword = true; //控制是否打印空格?
	while (stream >> word) {
		if (firstword) { firstword = false; }
		else {cout << " "; }
		cout << transfer(map, word);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值