复习第11章
单词转换程序
// p391.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<map>
#include<vector>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
//从文件中读取存储规则,建立关系map
void SetRelation(ifstream &in, map<string, string>&rel)
{
string line;
while (getline(in, line))
{
string key, akey;
istringstream word(line);
word >> key>>akey;
char a;
while((a=word.get()) != -1)
{
string str;
word >> str;
akey =akey+" "+ str;
}
rel[key] = akey;
}
}
int main(int argc, char *argv[])
{
ifstream in("text.txt");
map<string, string>ss;
SetRelation(in, ss);
ifstream fileIn("kewen.txt");
string word;
while (fileIn>> word)
{
auto pt=ss.find(word);
if (pt != ss.end())
{
word = ss[word];
}
cout << word;
char a = fileIn.get();
if (a == ' ')
cout << ' ';
else if (a == '\n')
cout << endl;
}
system("pause");
return 0;
}
与课本程序区别:
(1)空格和换行的输出控制
课本是逐行获取来控制换行,通过布尔标志控制空格,true 与false交替
(2)建立映射
关键字和值中,值的获取通过getline,但是需要注意第一个空格需要去除。而我是通过string相加