用map的单词转换以及文件打开的相对路径问题


#include <iostream> #include <map> #include <fstream> #include <sstream> #include <string> using namespace std; map<string,string> buildMap(ifstream & map_file) { map<string,string> trans_map; string key; string value; while(map_file>>key && getline(map_file,value))//! first word : key,the rest : value { if(value.size()>1){ trans_map[key] = value.substr(1); }else{ throw runtime_error("no rule for" + key); } } return trans_map; } const string & transform(const string& word, const map<string,string> & m) { auto map_it = m.find(word); if(map_it != m.cend()) { return map_it->second; }else{ return word; } } void word_transform(ifstream &map_file, ifstream &input) { auto trans_map= buildMap(map_file); string text; while(getline(input,text)) { std::istringstream stream(text); string word; bool firstWord = true; while(stream >> word) { if(firstWord) firstWord = false; else cout << " "; cout<< transform(word,trans_map); } cout<<endl; } } int main() { ifstream ifs_map("word_transformation_bad.txt"), ifs_content("given_to_transform.txt"); if (ifs_map && ifs_content) word_transform(ifs_map, ifs_content); else std::cerr << "can't find the documents." << std::endl; // map<string,int> msi = { {"sdji",2},{"bdsdad",3}}; // auto c= msi.find("sdji"); // // auto lb = msi.lower_bound("bdsda"); // cout<<lb->second; // cout << "Hello world!" << endl; return 0; }

 来自C++Primer,我对文件读写不是特别熟悉,ifstream的文件打开可以相对路径可以绝对路径,这里是一个相对路径的版本,只要和主程序放在同一个文件夹就可以了

 向下就直接 /

    ifstream ifs_map("data/word_transformation_bad.txt"),
        ifs_content("data/given_to_transform.txt");

向上一级就 ../ 

    ifstream ifs_map("../data/word_transformation_bad.txt"),
        ifs_content("../data/given_to_transform.txt");

猜你喜欢

转载自www.cnblogs.com/FlyingZiming/p/11748201.html