๐Word Count LabLAB
Word Count Lab
Build a wordcount program that reads a text file and reports its line count and word count.
Program behaviour
Read the file path from os.Args[1]. Count:
- Lines: number of newline-terminated lines (count how many times \n appears, or use a Scanner)
- Words: number of whitespace-separated tokens across all lines
Print the result in exactly this format:
Implementation steps
- Read
os.Args[1]as the file path - Open the file with
os.Open(rememberdefer f.Close()) - Use
bufio.Scannerto read line by line - For each line, use
strings.Fieldsto split into words and accumulate the count - After the loop, print
Lines: N, Words: M
Handling an empty file
An empty file should print:
Testing in main
Since the Playground can't read from disk, simulate the input with strings.NewReader:
Your countLines / main logic should accept an io.Reader so it works with both a real file and the test input.
โ Enter (Mac) ยท Ctrl+Enter (Win/Linux)
โ Enter (Mac) ยท Ctrl+Enter (Win/Linux)