Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different.

Similar presentations


Presentation on theme: "Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different."— Presentation transcript:

1 Lists and Strings Chapter 6

2 Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different ways. – Contiguous – Simply linked list – Doubly linked list Implement a string library. Combine the string and list libraries to create a file editing program.

3 Homework Overview Written (max 8 points) – 6.1 E1(4 pts) – 6.1 E4(4 pts) – 6.1 E7(4 pts) Programming (max 30 points) – 6.3 E1(a, d)(8 pts) – 6.3 E2(8 pts) – 6.3 E3 (a,b, c)(10 pts) – 6.4 P1(15 pts) Group Projects (55 points) – 6.2 E1, P1(15 pts) – 6.2 E3 (c, e, i, l), E4, P3(b) (20 pts) – 6.2 E5 (c, e, i, l, m), P3(c)(20 pts)

4 General Lists In a general list operations can take place at any point, not just the beginning and end. A list of elements is a finite sequence of elements that supports the following operations: – Construct and empty list. – Determine if the list is empty. – Determine if the list is full. – Find the size of the list. – Clear the list. – Insert an entry at a specified position. – Remove an entry from a specified position. – Retrieve the data from the entry at a specified position. – Replace an entry at a specified position. – Traverse the list, performing a given operation on each entry.

5 Specifying a Position To specify a location in the list we will indicate its position with an integer 0 through size-1 (similar to indexing). The methods will have the following signatures: –List::List(); –void List::clear(); –bool List::empty() const; –bool List::full() const; –int List::size() const; –Error_code List::insert(int position, const List_entry &x); –Error_code List::remove(int position, List_entry &x); –Error_code List::retrieve(int position, List_entry &x) const; –Error_code List::replace(int position, const List_entry &x); –void List::traverse(void (*visit)(List_entry &)); Notice that traverse takes a function pointer as a parameter. – This function will be applied to every entry in the list. – Note the book uses the pointer notation – this could be done without using pointer notation.

6 Homework – Section 6.1 (page 217) Written – E1 (written on paper, use calls to the methods described in the book.) (4 pts) – E4 (written on paper) (4 pts) – E7 (written on paper) (4 pts)

7 Class Templates Rather than use a typedef to set to the data to be stored in the list, it is cleaner to use class templates. The class will look like the following: template class List {... };}; The methods will have the following form: template int List ::size() const {... };

8 Implementation Options There are 3 options to implement our list class. 1.A contiguous implementation. – Simple to implement. – Insertions and removals are slow – similar to a queue. 2.A simply linked list. – Similar to a stack or queue. 3.A doubly linked list. – More on this later.

9 Contiguous List Class enum Error_code {success, fail, overflow, range_err}; // The possible error conditions const int max_list = 10; // Use a small value for testing template class List { public: List(); // constructor /* Stub */ int size() const; /* Post: Return the size of the List. */ bool full() const; /* Stub */ bool empty() const; /* Stub */ void clear(); /* Stub */

10 Contiguous List Class void traverse(void (*visit)(List_entry &)); /* Post: The function *visit is applied to every entry in the list. */ Error_code retrieve(int position, List_entry &x) const; /* Stub */ Error_code replace(int position, const List_entry &x); /* Stub */ Error_code remove(int position, List_entry &x); /* Stub */ Error_code insert(int position, const List_entry &x); /* Post: If the List is not full and 0 <= position <= count the function succeeds. Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */ protected: int count; List_entry entry[max_list]; };

11 Contiguous List Methods template Error_code List ::insert(int position, const List_entry &x) /* Post: If the List is not full and 0 <= position <= count the function succeeds. Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */ { if (full()) return overflow; if (position count) return range_err; for (int i = count - 1; i >= position; i--) entry[i + 1] = entry[i]; entry[position] = x; count++; return success; }

12 Contiguous List Methods template int List ::size() const /* Post: Return the size of the List. */ { return count; } template void List ::traverse(void (*visit)(List_entry &)) /* Post: The function *visit is applied to every entry in the list. */ { for(int i = 0; i < count; i++){ (*visit)(entry[i]); } } Note the stubs have been omitted.

13 List Driver Program typedef char List_entry; int main() /* Post: Accepts commands from user as a menu-driven demonstration program for the class List. Uses: The class List and the funcitons introduction, get_command, and do_command. */ { List test_list; introduction(); while (do_command(get_command(), test_list)); }

14 List Driver Program void help() /* Post: A help screen for the program is printed, giving the meaning of each command that the user may enter.*/ { cout << endl << "This program allows the user to enter one command" << endl << "(but only one) on each input line." << endl << "For example, if the command G is entered, then" << endl << "the program will retreive an entry from the list." << endl << endl << "The valid commands are:" << endl << "I - Insert a entry into the list" << endl << "D - Delete an entry from the list" << endl << "R - Replace an entry in the list" << endl << "G - Get an entry from the list" << endl << "P - Print the list" << endl << "H - This help screen" << endl << "Q - Quit" << endl to continue." << flush; char c; cin.get(c); // flush out an extra newline do { cin.get(c); } while (c != '\n'); }

15 List Driver Program char get_command() /* Post: The user enters a command (I, D, R, G, P, H, Q, i, d, r, g, p, h, or q). The function returns the command entered. */ { char command; bool waiting = true; cout :"; while (waiting){ cin >> command; command = tolower(command); if (command == 'i' || command == 'd' || command == 'r' || command == 'g' || command == 'p' || command == 'h' || command == 'q') waiting = false; else { cout << "Please enter a valid command:" << endl << "[I]insert [D]delete [R]replace" << endl << "[G]get [P]print [H]Help" << endl << "[Q]uit." << endl; } } return command; }

16 List Driver Program bool do_command(char c, List &test_list) /* Pre: c represents a valid command. Post: Performs the given command c on the List test_list. Returns false if c == 'q', otherwise returns true. Uses: The class List. */ { bool continue_input = true; int position; List_entry x; Error_code err; switch (c) { case 'i': cout << "Please enter a position to insert the new entry: " << flush; cin >> position; cout << "Please enter a new character to insert into the List: " << flush; cin >> x; err = test_list.insert(position, x); if (err == overflow) cout << "List is full." << endl; if (err == range_err) cout << "Position is not valid." << endl; break;

17 List Driver Program case 'd': cout << "Please enter a position to delete: " << flush; cin >> position; err = test_list.remove(position, x); if (err == range_err) cout << "Position is not valid." << endl; else cout << "The removed entry was " << x << "." << endl; break; case 'r': cout << "Please enter a position to replace: " << flush; cin >> position; cout << "Please enter a new character to put in this position: " << flush; cin >> x; err = test_list.replace(position, x); if (err == range_err) cout << "Position is not valid." << endl; break;

18 List Driver Program case 'g': cout << "Please enter a position to get: " << flush; cin >> position; err = test_list.retrieve(position, x); if (err == range_err) cout << "Position is not valid." << endl; else cout << "The entry is " << x << "." << endl; break; case 'p': test_list.traverse(print); cout << endl; break; case 'h': help(); break; case 'q': cout << "List demonstration finished." << endl; continue_input = false; break; } return continue_input; }

19 List Driver Program void print(List_entry &x) { cout << x << " "; } Note: this function is only used as a parameter for traverse.

20 Homework – Section 6.2 (page 231) Group Project – E1, P1 (email code) (15 pts)

21 Simply Linked Lists The second option for our list class is the simply linked list. Similar to a stack or queue. We could maintain a pointer to the current location.

22 Nodes We modify the node class to add templates. template struct Node{ // data members Node_entry entry; Node *next; // constructors Node(); /* Post: an empty node is created that has no next or previous nodes. */ Node(Node_entry item, Node *link = NULL); /* Post: a node is created that contains the entry item and has the node link as the next node. */ }; template Node ::Node() /* Post: an empty node is created that has no next node. */ { next = NULL; } template Node ::Node(Node_entry item, Node *link) /* Post: a node is created that contains the entry item and has the node link as the next node. */ { entry = item; next = link; }

23 Simply Linked List Class In the simply linked class definition all the public methods are the same. – These classes are functional replacements for each other. – Only the protected data changes. – In this implementation there is also a protected helper function. protected: int count; mutable int current_position; Node *head; mutable Node *current; void set_position(int position) const; /* Pre: Position is a valid position in the List: 0 <= position < count. Post: The current Node pointer references the Node at position. */

24 Mutable Keyword Notice that current_position and current are mutable. This means that these variables can be changed by constant functions. – This makes sense; changing these really doesn’t change the list. – We may want to change these in some of our constant functions like retrieve.

25 Simply Linked List Methods template Error_code List ::insert(int position, const List_entry &x) /* Post: If the List is not full and 0 <= position <= count the function succeeds. Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */ { if (position count) return range_err; Node *new_node, *previous, *following; if (position > 0) { set_position(position - 1); previous = current; following = previous->next; } else following = head; new_node = new Node (x, following); if (new_node == NULL) return overflow; if (position == 0) { head = new_node; current_position = 0; current = head; } else previous->next = new_node; count++; return success; }

26 Simply Linked List Methods template Error_code List ::retrieve(int position, List_entry &x) const /* Post: The entry at the indicated position has been retrieved to the output parameter x. If position is out of bounds an Error_code of range_err is returned. */ { if (position = count || empty()) return range_err; set_position(position); x = current->entry; return success; } template bool List ::empty() const /* Post: If the List is empty, true is returned. Otherwise false is returned. */ { return (count == 0); } template int List ::size() const /* Post: Return the size of the List. */ { return count; }

27 Simply Linked List Methods template List ::List() // Constructor /* Post: The List is initialized to be empty.*/ { head = NULL; count = 0; } template List ::~List() // Destructor /* Post: The List has been destroyed and its memory freed. */ { clear(); } template List ::List(const List &original) // copy constructor /* Post: The List is initialized as a copy of List original. */ { List_entry x; count = 0; head = NULL; for (int i = 0; i < original.count; i++){ original.retrieve(i, x); insert(i, x); } }

28 Simply Linked List Methods template void List ::set_position(int position) const /* Pre: Position is a valid position in the List: 0 <= position < count. Post: The current Node pointer references the Node at position. */ { if (position < current_position){ // must start over at head of list current_position = 0; current = head; } for (; current_position != position; current_position++) current = current->next; } The same driver is used for all three implementations of the list package.

29 Homework – Section 6.2 (page 231) Group Project – E3 (c, e, i, l), E4, P3(b) (email code) (20 pts)

30 The Problem Simply Linked Lists There is a problem with our simply linked list package. Suppose we want to delete the current entry “C”. – We need to make the pointer from “B” go to “D”. – The only way to get to “B” is to start at the head and work through the list until we find it. – Look at the code for set_position. – To go earlier in the list than the current position it is necessary to start over at the head. It would be nice if we could go backward from “C” to “B”.

31 Doubly Linked Lists Our third implementation is a doubly linked list. We can store an additional pointer in each node that goes backward in the list.

32 Removing an Entry Removing an entry will be fast. – No need to search from the beginning. Removing an entry will be more complicated. – More pointers to reroute. – Using a temporary pointer to keep track of the node to be deleted would be a good idea.

33 Inserting an Entry Inserting an entry is similar.

34 Doubly Linked Nodes template struct Node{ // data members Node_entry entry; Node *next; Node *back; // constructors Node(); /* Post: an empty node is created that has no next or previous nodes. */ Node(Node_entry item, Node *link_back = NULL, Node *link_next = NULL); /* Post: a node is created that contains the entry item and has the node at link_back as the back node and link_next as the next node. */ };

35 Doubly Linked Nodes template Node ::Node() /* Post: an empty node is created that has no next node. */ { next = NULL; back = NULL; } template Node ::Node(Node_entry item, Node *link_back, Node *link_next) /* Post: a node is created that contains the entry item and has the node at link_back as the back node and link_next as the next node. */ { entry = item; next = link_next; back = link_back; }

36 Doubly Linked List Class Again, all the public methods have the same signatures. The protected data is somewhat different. – There is no need to remember the location of the head of the list. – We can do everything using the current pointer. protected: int count; mutable int current_position; mutable Node *current; void set_position(int position) const; /* Pre: Position is a valid position in the List: 0 <= position < count. Post: The current Node pointer references the Node at position. */

37 Doubly Linked List Methods template Error_code List ::insert(int position, const List_entry &x) /* Post: If the List is not full and 0 <= position <= count the function succeeds. Any entry formerly at position and all later entries have their position increased by 1 and x is inserted at position of the List. Else: the function fails with a diagnostic error code. */ { Node *new_node, *following, *preceding; if (position count) return range_err; if (position == 0) { if (count == 0) following = NULL; else { set_position(0); following = current; } preceding = NULL; } else { set_position(position - 1); preceding = current; following = preceding->next; }

38 Doubly Linked List Methods new_node = new(nothrow) Node (x, preceding, following); if (new_node == NULL) return overflow; if (preceding != NULL) preceding->next = new_node; if (following != NULL) following->back = new_node; current = new_node; current_position = position; count++; return success; }

39 Doubly Linked List Methods template List ::List() // Constructor /* Post: The List is initialized to be empty.*/ { count = 0; } template List ::List(const List &original) // copy constructor /* Post: The List is initialized as a copy of List original. */ { List_entry x; count = 0; current = NULL; for (int i = 0; i < original.count; i++){ original.retrieve(i, x); insert(i, x); } }

40 Doubly Linked List Methods template void List ::set_position(int position) const /* Pre: Position is a valid position in the List: 0 <= position < count. Post: The current Node pointer references the Node at position. */ { if (current_position <= position) for (; current_position != position; current_position++) current = current->next; else for(; current_position != position; current_position--) current = current->back; } Several methods do not change between implementations and are not listed here. – The destructor –retrieve –empty –size

41 Homework – Section 6.2 (page 231) Group Project – E5 (c, e, i, l, m), P3(c) (email code) (20 pts)

42 String Library Now let’s turn to implementing strings. What operations would we want strings to support? – Overload assignment operator – Copy constructor – Destructor – Constructor (with and without parameters) – Overload other operators (, =, ==, !=) We would like for the following code to work as expected. String s1(“something”); String s2; s2 = “something else”; s1 = s2;

43 String Conversions It would be nice if there were conversions between C-strings and our new string type. Convert a C-string to a String. String s = “something”; Convert a String to a C-string. const char *new_string = s.c_str(); The return value from the c_str method should be a C-string of constant characters. – This needs to be constant because it is just going to be a pointer to the data in the string object, not a copy.

44 Other String Operations There are more operations that we might like for our strings. – Concatenation – Read in from input stream – Print to output stream – Read until a separator character is reached – Copy a string – Copy part of a string – Search for a substring – etc.

45 String Class class String { public: String();// constructor /* Post: The String is initialized to be empty. */ ~String();// destructor /* Post: The String is deleted and its memory freed. */ String (const String &original); // copy constructor /* Post: The String is initialized to be a copy of the String original. */ String (const char *in_string); // conversion from C-string /* Pre: The pointer in_string references a C-string. Post: The String is initialized by the C-string in_string. */ String (list &in_list);// conversion from List /* Pre: The String is initialized by the character List in_list. */ const String& operator = (const String &original);// overload assignment operator /* Post: The String is reset as a copy of the String original. */ const char *c_str() const; // conversion to C-style string /* Post: A pointer to a legal C-string object matching the String is returned. */ protected: char *entries; int length; };

46 More String Operators The remaining operators do not modify their arguments and so do not need to be methods of the class. bool operator == (const String &first, const String &second); /* Post: Return true if the String first agrees with String second. Else: Return false. */ bool operator > (const String &first, const String &second); /* Stub */ bool operator < (const String &first, const String &second); /* Stub */ bool operator >= (const String &first, const String &second); /* Stub */ bool operator <= (const String &first, const String &second); /* Stub */ bool operator != (const String &first, const String &second); /* Stub */

47 More String Functions void strcat(String &add_to, const String &add_on); /* Post: The function concatenates String add_on onto the end of String add_to. */ String read_in(istream &input); /* Post: Return a String read (as characters terminated by a newline or an end-of- file character) from an istream parameter. */ String read_in(istream &input, int &terminator); /* Post: Return a String read (as characters terminated by a newline or an end-of- file character) from an istream parameter. The terminating character is recorded as the output parameter terminator. */ void write(String &s); /* Post: The String parameter s is written to cout. */ void strcpy(String &copy, const String &original); /* Post: The function copies String original to String copy. */ /* Stub */ void strncpy(String &copy, const String &original, int n); /* Post: The function copies at most n characters from String original to String copy. */ /* Stub */ int strstr(const String &text, const String &target); /* Post: If String target is a substring of String text, the function returns the array index of the first occurrence of string stored in target in the string stored in text. Else: The function returns a code of -1. */ /* Stub */

48 String Methods String::~String () /* Post: The String is deleted and its memory freed. */ { delete []entries; } String::String(const String &original) /* Post: The String is initialized to be a copy of the String original. */ { length = original.length; entries = new char[length + 1]; strcpy(entries, original.entries); } String::String (const char *in_string) /* Pre: The pointer in_string references a C-string. Post: The String is initialized by the C-string in_string. */ { length = strlen(in_string); entries = new char[length + 1]; strcpy (entries, in_string); }

49 String Methods String::String (list &in_list) /* Pre: The String is initialized by the character list in_list. */ { length = in_list.size(); entries = new char[length + 1]; for (int i = 0; i < length; i++){ entries[i] = in_list.front(); in_list.pop_front(); } entries[length] = '\0'; } const char* String::c_str() const /* Post: A pointer to a legal C-string object matching the String is returned. */ { return (const char *) entries; }

50 More String Operators The comparison operators can all use the c_str method and then functions contained in the cstring library to make their comparisons. – They do not need access to private data, so they do not need to be member functions. bool operator == (const String &first, const String &second) /* Post: Return true if the String first agrees with String second. Else: Return false. */ { return strcmp(first.c_str(), second.c_str()) == 0; }

51 More String Functions The rest of the string function can use methods to do their jobs, so they do not need to be methods themselves. void strcat(String &add_to, const String &add_on) /* Post: The function concatenates String add_on onto the end of String add_to. */ { const char *cfirst = add_to.c_str(); const char *csecond = add_on.c_str(); char *copy = new char[strlen(cfirst) + strlen(csecond) + 1]; strcpy(copy, cfirst); strcat(copy, csecond); add_to = copy; // This uses the C-string conversion constructor and the overlaoded = operator delete []copy; } String read_in(istream &input) /* Post: Return a String read (as characters terminated by a newline or an end-of- file character) from an istream parameter. */ { list temp; int size = 0; char c; while ((c = input.peek()) != EOF && (c = input.get()) != '\n') { temp.push_back(c); size++; } String answer(temp); return answer; }

52 More String Functions String read_in(istream &input, int &terminator) /* Post: Return a String read (as characters terminated by a newline or an end-of- file character) from an istream parameter. The terminating character is recorded as the output parameter terminator. */ { list temp; int size = 0; char c; while ((c = input.peek()) != EOF && (c = input.get()) != '\n') { temp.push_back(c); size++; } if (c == '\n') terminator = '\n'; else terminator = EOF; String answer(temp); return answer; } void write(String &s) /* Post: The String parameter s is written to cout. */ { cout << s.c_str() << endl; }

53 Homework – Section 6.3 (page 241) Programming – E1(a,d) (email code, be sure to test) (8 pts) – E2 (email code) (8 pts) – E3 (a, b, c) (email code) (10 pts)

54 Text Editor We can use our general list class and the string class to create a basic text editor. A text editor is a simple word processor. – It generally doesn’t have a lot of formatting features. – It often adds features to make programming easier. Highlight keywords Catch missing brackets etc. Our editor will store text as a list of lines of text (paragraph) where each line is a string.

55 Editor Class The editor class is actually an extension of the list class. It adds methods: – A new constructor – Get commands – Execute commands It adds private data: – Command – Input stream – Output stream A whole raft of helper functions are also added to operate on the list of lines.

56 Editor Class Editor: public List { public: Editor(ifstream *file_in, ofstream *file_out); /* Post: Initialize the Editor members infile and outfile with the parameters. */ bool get_command(); /* Post: Sets member user_command; returns true unless the user's command is q. Uses: C library function tolower. */ void run_command(); /* Post: The command in user_command has been performed. Uses: Methods and auxiliary functions of the class Editor, the class String, and String processing functions. */ private: ifstream *infile; ofstream *outfile; char user_command;

57 Editor Class Helper Functions Error_code next_line(); Error_code previous_line(); Error_code goto_line(); Error_code insert_line(); Error_code substitute_line(); Error_code change_line(); void read_file(); void write_file(); void find_string(); };

58 Editor Class Methods Editor::Editor(ifstream *file_in, ofstream *file_out) /* Post: Initialize the Editor members infile and outfile with the parameters. */ { infile = file_in; outfile = file_out; } bool Editor::get_command() /* Post: Sets member user_command; returns true unless the user's command is q. Uses: C library function tolower. */ { if (count > 0) // Different from version in Book cout << current_position << ":" entry.c_str() << "\n??" << flush; else cout << "File is empty.\n??" << flush; cin >> user_command; // ignores white space and gets command user_command = tolower(user_command); while (cin.get() != '\n') ; // ignore user's enter key if (user_command == 'q') return false; else return true; }

59 Editor Class Methods void Editor::run_command() /* Post: The command in user_command has been performed. Uses: Methods and auxiliary functions of the class Editor, the class String, and String processing functions. */ { String temp_string; switch (user_command){ case 'b': if (empty()) cout << " Warning: Empty buffer" << endl; else while (previous_line() == success) ; break; case 'c': if (empty()) cout << " Warning: Empty file" << endl; else if (change_line() != success) cout << "Error: Substitution failed" << endl; break; case 'd': if (remove(current_position, temp_string) != success) cout << " Error: Deletion failed" << endl; break;

60 Editor Class Methods case 'e': if (empty()) cout << " Warning: Empty buffer" << endl; else while (next_line() == success) ; break; case 'f': if (empty()) cout << " Warning: Empty file" << endl; else find_string(); break; case 'g': if (goto_line() != success) cout << " Warning: No such line" << endl; break; case '?': case 'h': cout << "Valid commands are b(egin) c(hange) d(el) e(nd)" << endl << "f(ind) g(o) h(elp) i(nsert) l(ength) n(ext) p(rior)" << endl << "q(uit) r(ead) s(ubsitute) v(iew) w(rite)" << endl; break; case 'i': if (insert_line() != success) cout << " Error: Insertion failed" << endl; break;

61 Editor Class Methods case 'e': case 'l': cout << "There are " << size() << " lines in the file." << endl; if (!empty()) cout << "Current line length is " entry).c_str()) << endl; break; case 'n': if (next_line() != success) cout << " Warning: At end of buffer" << endl; break; case 'p': if (previous_line() != success) cout << " Warning: At start of buffer" << endl; break; case 'r': read_file(); break; case 's': if (substitute_line() != success) cout << " Error: Substitution failed" << endl; break; case 'v': traverse(write); break;

62 Editor Class Methods case 'w': if (empty()) cout << " Warning: Empty file" << endl; else write_file(); break; default: cout << "Press h or ? for help or enter a valid command:"; } } Error_code Editor::insert_line() /* Post: A string entered by the user is inserted as a user-selected line number. Uses: String and Editor methods and functions. */ { int line_number; cout << " Insert what line number? " << flush; cin >> line_number; while (cin.get() != '\n'); cout << " What is the new line to insert? " << flush; String to_insert = read_in(cin); return insert(line_number, to_insert); }

63 Editor Class Methods Error_code Editor::change_line() /* Pre: The Editor is not empty. Post: If a user-specified string appears in the current line, it is replaced by a new user-selected string. Else: an Error_code is returned. Uses: String and Editor methods and functions. */ { Error_code result = success; cout << " What text segment do you want to replace? " << flush; String old_text = read_in(cin); cout << " What new text segment do you want to add in? " << flush; String new_text = read_in(cin); int index = strstr(current->entry, old_text); if (index == -1) result = fail; else { String new_line; strncpy(new_line, current->entry, index); strcat(new_line, new_text); const char *old_line = (current->entry).c_str(); strcat(new_line, (String)(old_line + index + strlen(old_text.c_str()))); current->entry = new_line; } return result; }

64 Editor Class Methods void Editor::read_file() /* Pre: Either the Editor is empty or the user authorizes the command. Post: The contents of *infile are read to the Editor. Any prior contents of the Editor are overwritten. Uses: String and Editor metohds and functions. */ { bool proceed = true; if (!empty()) { cout << "Buffer is not empty; the read will destroy it." << endl; cout << " OK to proceed?" << endl; if (proceed = user_says_yes()) clear(); } int line_number = 0, terminal_char; while (proceed) { String in_string = read_in(*infile, terminal_char); if (terminal_char == EOF) { proceed = false; if (strlen(in_string.c_str()) > 0) insert(line_number, in_string); } else insert(line_number++, in_string); } }

65 Editor Class Methods void Editor::find_string() /* Pre: The Editor is not empty. Post: The current line is advanced until either it contains a copy of a user- selected string or it reaches the end of the Editor. If the selected string is found, the corresponding line is printed with the string highlighted. Uses: String and Editor methos and functions. */ { int index, length; cout << "Enter string to search for:" << endl; String search_string = read_in(cin); length = strlen(search_string.c_str()); // Different than version in the Book while ((index = strstr(current->entry, search_string)) == -1) if (next_line() != success) break; if (index == -1) cout << "String was not found."; else { cout entry).c_str() << endl; for (int i = 0; i < index; i++) cout << " "; for (int j = 0; j < length; j++) // Different than version in the Book cout << "^"; } cout << endl; }

66 Homework – Section 6.4 (page 250) Programming – P1 (email code) (15 pts)


Download ppt "Lists and Strings Chapter 6. Objectives Discuss general list abstract data type. Implement class templates. Implement the general list three different."

Similar presentations


Ads by Google