(E) Word counter line by line¶
Goal: I will go through file reading once more. I will practice combining different STL containers.
Instructions:
Create a new project: student/05/wordcount/
.
Write a program that counts the amount of those lines in a file that contain the words you have chosen, and prints the line numbers and amounts of each word in the file in alphabetical order. (Please note: even if a word appears several times on a line, it should be counted only once.)
After startup, the program asks for the name of the file.
If the file cannot be opened, the program prints the error message
”Error! The file <filename> cannot be opened.
”, where
<filename>
is replaced with the name of the file.
Then, the program terminates with the return value EXIT_FAILURE
.
The program prints the words contained in the file, each on a line
of their own.
The first thing on the line is the word in question, then
space, amount of lines with that word, and a colon.
The last items are the line numbers with that word, separated with
spaces and commas.
After that, the program exits with the return value EXIT_SUCCESS
.
As an example of how the program should work, consider the following case.
If the contents of the file highway.txt
are:
I'm on a high way to hell
I'm on a high way to hell
It's going really well
Well it's only hell
then the program will work like this:
Input file: highway.txt
I'm 2: 1, 2
It's 1: 3
Well 1: 4
a 2: 1, 2
going 1: 3
hell 3: 1, 2, 4
high 2: 1, 2
it's 1: 4
on 2: 1, 2
only 1: 4
really 1: 3
to 2: 1, 2
way 2: 1, 2
well 1: 3
If the file not_a_file.txt
does not exist, the program
will work like this:
Input file: not_a_file.txt
Error! The file not_a_file.txt cannot be opened.
Tips for completing the assignment:
- Think carefully about which data structure you choose. Choosing the right structure will save you a lot of trouble.
- Remember to change the execution folder of your program so that the program can find the text files you are using. You can read about how to do this in the assignment Line numbering a file.
A+ presents the exercise submission form here.