-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_count.go
46 lines (38 loc) · 1008 Bytes
/
word_count.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
// Prompt the user to enter the filename
fmt.Print("Enter the filename: ")
var filename string
fmt.Scanln(&filename)
// Open the file
file, err := os.Open(filename)
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
// Create a scanner to read from the file
scanner := bufio.NewScanner(file)
// Initialize word count variable
wordCount := 0
// Scan through the file line by line
for scanner.Scan() {
// Split each line into words
words := strings.Fields(scanner.Text())
// Increment the word count by the number of words in the line
wordCount += len(words)
}
// Check for any errors encountered during scanning
if err := scanner.Err(); err != nil {
fmt.Println("Error:", err)
return
}
// Print the word count
fmt.Println("Word count:", wordCount)
}