1: // Filename: REVSTR1.CPP
2: // Purpose: Reads in a string and writes it out reversed.
4: #include <iostream>
5: #include <string>
7: String reversedString(String s)
8: // Pre: The string "s" has been initialized.
9: // Post: The function value is a string which is the input
10: // string with its characters in reverse order.
11: {
12: String r = "";
13: String ch;
14: int i;
15: for (i = 0; i < s.length(); i++)
16: {
17: ch = s(i, 1);
18: r = ch + r;
19: }
20: return r;
21: }
24: int main()
25: {
26: cout << endl
27: << "This program reads in a string (the "
28: << "maximum length is 20 characters) and " << endl
29: << "and then prints out the string reversed." << endl
30: << endl;
31: cout << "So, enter any string of up to 20 characters: " << endl;
33: String s;
34: cin.getline(s, 21, '\n');
36: cout << endl;
37: cout << "===== The string on the next line ... " << endl
38: << s << endl
39: << "===== when reversed, becomes:" << endl
40: << reversedString(s) << endl
41: << endl;
43: return 0;
44: }