Source of vector17.cpp


  1: //vector17.cpp

  3: #include <iostream>
  4: #include <fstream>
  5: #include <string>
  6: #include <vector>
  7: using namespace std;

  9: int main()
 10: {
 11:     cout << "\nThis program illustrates a vector of strings. It shows "
 12:         "how to read the lines\nof a textfile into a vector of strings "
 13:         "and then display the contents of the\nresulting vector on the "
 14:         "screen. It thus provides a simple \"display textfile\"\nroutine. "
 15:         "The user is asked to enter the name of the textfile and choose "
 16:         "how\nmany lines to show at a time.";
 17:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 19:     vector<string> lineList;
 20:     string fileName;
 21:     int numLinesToDisplay;

 23:     cout << "\nEnter name of file to display "
 24:         "(include full path if necessary):\n";
 25:     getline(cin, fileName);
 26:     cout << "How many lines do you want to see at once? ";
 27:     cin >> numLinesToDisplay; cin.ignore(80, '\n');

 29:     ifstream inFile(fileName.c_str());
 30:     string line;
 31:     while(getline(inFile, line)) lineList.push_back(line);
 32:     int lineCount = 0;
 33:     for (vector<string>::size_type i=0; i<lineList.size(); i++)
 34:     {
 35:         cout << lineList[i] << endl;
 36:         ++lineCount;
 37:         if (lineCount == numLinesToDisplay)
 38:         {
 39:             cout << "Press Enter to continue ... ";
 40:             cin.ignore(80, '\n');
 41:             lineCount = 0;
 42:         }
 43:     }
 44:     cout << "\n===== The entire file has now been displayed. =====\n";
 45:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 46: }