COMP2004 Programming Practice
2002 Summer School

Week 4 Friday Tutorial Exercises


  1. Write a program that reads words from std::cin (until there are none left) and then outputs a list of the words seen, along with the number of times each word was seen. For example,
    bash$ countwords
    hello there how are you?
    how how are there how how you are?
    Ctrl-D
    are : 2
    are? : 1
    hello : 1
    how : 5
    there : 2
    you : 1
    you? : 1
    bash$ 
    

  2. Write a concordance program. It should read text from std::cin, and output a list of words seen with the line numbers they were seen on. Chapter 7 of the textbook has an implementation of this which is a good starting point. For example,
    bash$ concordance
    hello there how are you?
    how how are there how how you are?
    Ctrl-D
    are : 1, 2
    are? : 2
    hello : 1
    how : 1, 2
    there : 1, 2
    you : 2
    you? : 1
    bash$ 
    

  3. Modify your Array class from last Wednesday's tutorial so that it throws an exception if an element that is out of bounds is accessed. It should be usable as follows:
    #include "Array.h"
    #include <iostream>
    
    int main() {
    	Array<const char*> s(3);
    	s[0] = "one";
    	s[1] = "two";
    	s[2] = "three";
    	s[3] = "four";     // this line should cause an exception to be thrown
    	for (int i = 0; i < s.size(); i++)
    		std::cout << s[i] << std::endl;
    }
    
    Also make sure that you can correctly catch the exception in main() and continue executing the program.