Program for word conversion using map
You must use the find function when searching words in a map. The following table cannot be used, because accessing nonexistent Elements Using subscript in a map will add a new element to the map container, the key of the new element is the content to be searched.
/*************************************** ************************************ <Br /> * Open File <br/> ******************************* **************************************** * *****/<br/> ifstream & open_file (ifstream & in, const string & file) <br/>{< br/> in. close (); // close in case it was already open <br/> in. clear (); // clear any existing errors </P> <p> // if the open fails, the stream will be in an in Valid state <br/> in. open (file. c_str (); // open the file we were given </P> <p> return in; // condition state is good if open succeeded <br/>}</P> <p> /****************** **************************************** * ***************** <br/> * word transform <br/> ********** **************************************** * *************************/<br/> void wordtransform (const string rule, const string infile) <br/> {<Br/> If (rule. empty () | infile. empty () <br/>{< br/> return; <br/>}</P> <p> Map <string, string> trans_map; <br/> string key, value; </P> <p> // open transformation file and check that open succeeded <br/> ifstream map_file; <br/> If (! Open_file (map_file, rule) <br/>{< br/> throw runtime_error ("no transformation file. "); <br/>}</P> <p> // read the transformation map and build the Map <br/> while (map_file> key> value) <br/>{< br/> trans_map.insert (make_pair (Key, value )); <br/>}</P> <p> // open the input file and check that the open succeeded <br/> ifstream input; <br/> If (! Open_file (input, infile) <br/>{< br/> throw runtime_error ("no input file. "); <br/>}</P> <p> string line; // hold each line from the input </P> <p> // read the text to transform it a line at a time <br/> while (Getline (input, line) <br/>{< br/> istringstream (line); // read the line a word at a time <br/> string word; <br/> bool bfirstwordflg = true; // controls whether a space is printed <br/> while (St Ream> word) <br/>{< br/> // OK: the actual mapwork, this part is the heart of the Program <br/> Map <string, string >:: const_iterator map_it = trans_map.find (Word); </P> <p> // if this word is in the transformation Map <br/> If (map_it! = Trans_map.end () <br/>{< br/> // replace it by the transformaion value in the Map <br/> word = map_it-> second; <br/>}</P> <p> If (bfirstwordflg) <br/>{< br/> bfirstwordflg = false; <br/>}< br/> else <br/>{< br/> cout <""; // print space between words <br/>}</P> <p> cout <word; <br/>}< br/> cout <Endl; // done with this line of input <br/>}< br/>