// 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);
}
}