Source of cstr3.cpp


  1: // Filename: CSTR3.CPP
  2: // Purpose:  Illustrates input of C-style strings with cin.get and
  3: //           with cin.getline.

  5: #include <iostream>
  6: #include <cstring>
  7: using namespace std;

  9: #include "PAUSE.H"

 11: int main()
 12: {
 13:     cout << endl;
 14:     cout << "This program illustrates input of C-strings "
 15:          << "with cin.get, as well as input "               << endl
 16:          << "of C-string \"lines\" with cin.getline.  "
 17:          << "Study the source code carefully while "        << endl
 18:          << "running it.  Note that you get to choose "
 19:          << "the string size, or the line size, "           << endl
 20:          << "on each pass.  When in one of the string-"
 21:          << "reading loops, at each pause you "             << endl
 22:          << "may either press ENTER to continue or "
 23:          << "enter an end-of-file to quit. "                << endl;
 24:     cout << endl;
 25:     Pause(0);  cout << endl;

 27:     char ch;

 29:     const int MAX_STR_SIZE = 10;
 30:     typedef char String10[MAX_STR_SIZE + 1];
 31:     String10 s1, s2;

 33:     int numChars;

 35:     do
 36:     {
 37:         cout << "Now reading with cin.get ..." << endl;
 38:         cout << "Enter the string size (<= " << MAX_STR_SIZE
 39:              << ") for this pass: ";
 40:         cin >> numChars;  cin.ignore(80, '\n');

 42:         cout << "Enter the strings below, on separate lines:" << endl;
 43:         cin.get(s1, numChars + 1);  cin.get(ch);
 44:         cin.get(s2, numChars + 1);  cin.get(ch);

 46:         cout << "The two strings are on the next two lines:" << endl;
 47:         cout << s1 << "<<" << endl;
 48:         cout << s2 << "<<" << endl;
 49:         Pause(0);  cout << endl;

 51:     } while (cin);

 53:     cout << endl;

 55:     cin.clear();


 58:     do
 59:     {
 60:         cout << "Now reading with cin.getline ..." << endl;
 61:         cout << "Enter the string size (<= " << MAX_STR_SIZE
 62:              << ") for this pass: ";
 63:         cin >> numChars;  cin.ignore(80, '\n');

 65:         cout << "Enter the two lines below: "   << endl;
 66:         cin.getline(s1, numChars + 1);
 67:         cin.getline(s2, numChars + 1);

 69:         cout << "Here are the two lines:" << endl;
 70:         cout << s1 << "<<" << endl;
 71:         cout << s2 << "<<" << endl;

 73:         Pause(0);  cout << endl;

 75:     } while (cin);

 77:     cout << endl;

 79:     return 0;
 80: }