I l@ve RuBoard Previous Section Next Section

Exercise 1.7

Using your favorite editor, type two or more lines of text into a file. Write a program to open the file, reading each word into a vector<string> object. Iterate over the vector, displaying it to cout. That done, sort the words using the sort() generic algorithm.



#include <algorithm> 


sort( container.begin(), container.end() ); 

Then print the sorted words to an output file.

I open both the input and the output file before reading in and sorting the text. I could wait to open the output file, but what would happen if for some reason the output file failed to open? Then all the computations would have been for nothing. (The file paths are hard-coded and reflect Windows conventions. The algorithm header file contains the forward declaration of the sort() generic algorithm.)



#include <iostream> 


#include <fstream> 


#include <algorithm> 


#include <string> 


#include <vector> 





using namespace std; 


int main() 


{ 


    ifstream in_file( "C:\\My Documents\\text.txt"  ); 


    if ( ! in_file ) 


       { cerr << "oops! unable to open input file\n"; return -1; } 





    ofstream out_file("C:\\My Documents\\text.sort" ); 


    if ( ! out_file ) 


       { cerr << "oops! unable to open input file\n"; return -2; } 





    string word; 


    vector< string > text; 


    while ( in_file >> word ) 


           text.push_back( word ); 





    int ix; 


    cout << "unsorted text: \n"; 





    for ( ix = 0; ix < text.size(); ++ix ) 


          cout << text[ ix ] << ' '; 


    cout << endl; 





    sort( text.begin(), text.end() ); 





    out_file << "sorted text: \n"; 


    for ( ix = 0; ix < text.size(); ++ix ) 


         out_file << text[ ix ] << ' '; 


    out_file << endl; 





    return 0; 


} 

The input text file consists of the following three lines:



we were her pride of ten she named us: 


Phoenix, the Prodigal, Benjamin, 


and perspicacious, pacific Suzanne. 

When compiled and executed, the program generates the following output (I've inserted line breaks to display it here on the page):



Benjamin, Phoenix, Prodigal, Suzanne. 


and her named of pacific perspicacious, 


pride she ten the us: we were 
    I l@ve RuBoard Previous Section Next Section