给定一个string,将它转换成另一个string。程序的输入是两个txt文件,第一个文件保存转换规则(如下WordMap.txt),用来转换第二个文件中的文本(如下InFile.txt)。WordMap.txt中每一行是一条转换规则,每条转换规则由两部分组成:一个单词和一个用来替换它的语句。要求:根据WordMap.txt中的转换规则,转换InFile.txt的内容,并将转换内容保存到output.txt文件中。
// WordMap.txt
brb be right back
k okay?
y why
r are
u you
pic picture
thk thanks!
18r later
hh ^-^
bsw best wishes!
// InFile.txt
where r u
y dont u send me a pic
k thk 18r
bsw hh
其程序如下:
// 单词转换程序
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
using namespace std;
map<string, string> bulidMap(ifstream &map_file);
void word_transform(ifstream &map_file, ifstream &input, ofstream &outFile);
int main()
{
cout << "main begin." << endl;
string strfile1("WordMap.txt");
string strfile2("InFile.txt");
string strfile3("output.txt");
ifstream mapFile(strfile1);
ifstream inFile(strfile2);
if (!mapFile.is_open() || !inFile.is_open())
{
cout << "Could not open the file named " << strfile1
<< " or named " << strfile2 << "." << endl;
}
ofstream outfile(strfile3);
if (outfile)
{
word_transform(mapFile, inFile, outfile);
}
mapFile.close();
inFile.close();
outfile.close();
cout << "main end." << endl;
return 0;
}
// 转换文本内容
void word_transform(ifstream &map_file, ifstream &input, ofstream &outFile)
{
map<string, string> trans_map;
try
{
trans_map = bulidMap(map_file);
}
catch(exception err)
{
cout << err.what() << endl;
return;
}
string text;
while (getline(input,text))
{
istringstream stream(text);
string word;
bool firstWord = false;
while (stream >> word)
{
map<string, string>::iterator itor = trans_map.find(word);
if (itor != trans_map.end())
{
outFile << itor->second;
}
else
{
outFile << word;
}
if (firstWord)
{
firstWord = false;
}
else
{
outFile << " ";
}
}
outFile << endl;
}
}
// 解析map文件
map<string, string> bulidMap(ifstream &map_file)
{
map<string, string> trans_map;
string key;
string value;
if (!map_file.is_open())
{
cout << "The map file is not open!" << endl;
return map<string, string>();
}
while (map_file >> key && getline(map_file, value))
{
if (value.size() >= 1)
{
string::size_type pos = value.find_first_not_of(' ');
if (pos != string::npos )
{
trans_map[key] = value.substr(pos);
}
else
{
throw runtime_error("no rule for key : " + key + ".");
}
}
else
{
throw runtime_error("no rule for key : " + key + ".");
}
}
return trans_map;
}
转换文本内容如下:
// outfile.txt
where are you
why dont you send me a picture
okay? thanks! later
best wishes! ^-^