This Lecture 18 Extra Credit assignment is worth up to 6 additional points towards the exercise category. You may earn partial credit for partially attempted/correct work. You may submit this extra credit until the normal EX18 deadline. Late submissions will not be accepted.
Goals¶
Write a small program using the C++ STL map
container and learn how to use C++ streams to read data from a file.
Description¶
Write a C++ program that reads a text file whose filename is given as a single command-line argument. The program should read and count the individual words in the file, and, after reading the entire file, it should print a list of the words sorted by the words, and the number of times each word appears in the file. Each word should be written on a separate output line with the word appearing first followed by a single space and the number of occurrences.
For example, if the file quotes.txt
contains
to be or not to be
to do is to be
to be is to do
do be do be do
then the output of ./ex18 quotes.txt
should begin with the following:
be 6
do 5
is 2
...
You should make the following assumptions:
- The file contains ASCII text – you do not need to verify this.
- Use the C++
>>
operator to read the input file one word (string) at a time. You may assume that each string read by>>
is a “word” for the purposes of this exercise – you do not need to do any additional processing to handle whitespace, punctuation, or similar issues. - Words must match exactly to be considered the same. Thus,
word
,Word
, andwoRD
are three different words because they contain different lower- and upper-case letters. - The list of words should be sorted using the ordinary ordering (i.e.,
<
) relation for strings. - Hints: Take advantage of the C++ STL library; one of the
map
containers should be particularly useful. For reading files, take a look at theifstream
class.
Requirements¶
Your code must:
- be contained in a single file called
ex18.cc
and compile without errors or warnings on Calgary using the commandg++ -g -Wall -std=c++17 -o ex18 ex18.cc
- have no crashes, memory leaks, or memory errors (hint: use
valgrind
) - be pretty: the formatting, modularization, variable and function names, use of const and so on (Hints: Google C++ Style Guide, cpplint)
- be robust: you should think about handling bogus input from the user (if any), and you should handle hard-to-handle cases (if there are any) gracefully.
You should submit your extra credit by manually uploading your ex18.cc
file to Gradescope. DO NOT submit via Gitlab.
Note
The autograder will show a default of 0 points for the total score. The staff will manually apply the appropriate amount of extra credit points toward your exercise grade.
Credit goes to Hal Perkins, UW CSE 333 instructor for authoring this exercise. Permission has been granted to use this exercise in CSE 374.