c++ primer中关于单词转换的程序

这是在第四版c++ primer书中第10章10.3.9的程序。觉得很好,记下来。

#include <iostream>
#include <map>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
using namespace std;
/*
in1.txt中的内容
'em	them
cuz	because
gratz	grateful
i	I
nah	no
pos	supposed
sez	said
tanx	thanks
wuz	was

in2.txt中的内容
nah i sez tanx cuz i wuz pos to
not cuz i wuz gratz
*/
ifstream& open_file(ifstream &in, const string &file) {
    in.close();//关闭以防之前已经打开
    in.clear();//清除任何存在的错误
    in.open(file.c_str());
    return in;//此时in要么已经与文件绑定在了一起,要么处于错误的状态
}
int main(int argc, char **argv)
{
    ifstream infile;
    ofstream outfile;
    map<string, string> wordChange;
    string input1 = "/home/xxx/Desktop/program/c++/单词转换/in1.txt";
    string input2 = "/home/xxx/Desktop/program/c++/单词转换/in2.txt";
    //infile.open(input1.c_str());
    if(!open_file(infile, input1)) cout << "no file" << endl;
    string key, value;
    while(infile >> key >> value) wordChange[key] = value;
    string line, word;
    //ifstream input(input2.c_str());
    ifstream input;
    if(!open_file(input, input2)) cout << "no file" << endl;
    map<string, string>::iterator iter;
    while(getline(input, line)) {
        istringstream stream(line);
        bool flag = true;
        while(stream >> word) {
            iter = wordChange.find(word);//此处不能用下标操作,因为下标操作会把原先没有的键值对加进去
            if(flag) {
                flag = false;
            } else {
                cout << " ";
            }
            if(iter != wordChange.end()) cout << iter->second;
            else cout << word;
        }
        cout << endl;
    }
    infile.close();
    return 0;
}

总结:文件操作用的还不是很好。linux下文件路径的问题,要注意用各种命令检查路径和权限。如ls, pwd, stat, cat 等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值