Practice
Word Count Across a File
2025/May/June·Variant 2
MEDIUMFile Handling
Write function CountWords(FileName) that opens a text file, reads it line by line, and returns the total number of space-separated words across the whole file. Each non-empty line has single spaces between words with no leading or trailing spaces; blank lines contain no words.
The test harness reads a number of lines from the user, writes them to report.txt, then calls CountWords("report.txt") and outputs the result.
Input: Number of lines, then each line of text. Output: The total word count.
Example:
Input: 2
The cat sat
A dog ran fast
Output: 7
Premium is coming soon. All grading features are currently unlocked.
Sample Test Cases
Test 1: Two lines of text
Inputs: 2, The cat sat, A dog ran fast
Expected: 7
Test 2: Single word
Inputs: 1, Hello
Expected: 1
Test 3: Three lines
Inputs: 3, One two three four five, Six seven, Eight
Expected: 8