//------------------------------------------------ // File: MaxString1.cpp // // Author: D. Frey // Date : 8/21/03 // Section: 1234 // Project: none // Description // This program is an example of using C++ string // objects. It includes string input (using the // >> extraction operator) and output, // string comparisons, strings as parameters and // function return values and manipulating indvidual characters // within a string //-------------------------------------------------- // This program reads strings from the user until // the user types "quit". It then prints the longest // string seen forwards and backwards //--------------------------------------------------- #include #include using namespace std; // prototypes for functions in this file string Reverse( string s); // constants in this file const string QUIT = "quit"; int main ( ) { string input; string longestString; // "priming read" for the while loop cout << "Please input a string:"; cin >> input; while (input != QUIT) { // check if the new string is longer than // longest seen so far if (input.size() > longestString.size()) longestString = input; // get the next string from the user cout << "Please input a string:"; cin >> input; } // reverse the string string backwards = Reverse( longestString ); // output string forwards and backwards cout << "\nThe longest string has " << longestString.size() << " characters\n"; cout << longestString << endl; cout << backwards << endl; cout << endl; return 0; } //----------------------------------- // Reverse // Preconditions: none // PostConditions: // returns the user supplied string // in reverse character order //----------------------------------- string Reverse (string s) { string result(s); // copy of original string int start = 0; // left-most character int end = s.length(); // right-most character // swap chars until end and start // meet in the middle while (start < end) { --end; char c = result[end]; result[end] = result[start]; result[start] = c; ++start; } return result; }