Source of revstr2.cpp


  1: // Filename: REVSTR2.CPP
  2: // Purpose:  Reads in a string and writes it out reversed.

  4: #include <iostream>

  6: void ReverseString(const char s[], char r[])
  7: // Pre:  The string "s" has been initialized.
  8: // Post: "r" contains the same characters as "s"
  9: //       but in reverse order. "s" is unchanged.
 10: {
 11:     int sLength = strlen(s);
 12:     int i;
 13:     char temp;
 14:     r[sLength] = '\0';
 15:     for (i = sLength-1; i >= 0; i--)
 16:         r[i] = s[sLength - 1 - i];
 17: }


 20: int main()
 21: {
 22:     cout << endl
 23:          << "This program reads in a string (the "
 24:          << "maximum length is 20 characters) and "     << endl
 25:          << "and then prints out the string reversed."  << endl
 26:          << endl;
 27:     cout << "So, enter any string of up to 20 characters: " << endl;

 29:     typedef char String20[21];
 30:     String20 s;
 31:     String20 r;
 32:     cin.getline(s, 21, '\n');
 33:     ReverseString(s, r);

 35:     cout << endl;
 36:     cout << "===== The string on the next line ... "  << endl
 37:          << s                                         << endl
 38:          << "===== when reversed, becomes:"           << endl
 39:          << r                                         << endl
 40:          << endl;

 42:     return 0;
 43: }