-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
86 lines (68 loc) · 1.72 KB
/
main.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Quizzes the user based on a csv file with 2 fields on each record(line)
// containing a problem and an answer.
package main
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"log"
"os"
"strings"
)
type problem struct {
statement string // User prompt
answer string // Correct Responce
}
func main() {
var filename string
// Uses 'problems.csv' if no argument is passed
if len(os.Args) == 1 {
filename = "problems.csv"
fmt.Println("No filename specified. Using 'problems.csv' for config file...")
} else {
filename = os.Args[1]
}
problems := readFromFile(filename)
r := bufio.NewReader(os.Stdin)
var right int
fmt.Print("\nQUIZ BEGIN\n\n")
for _, problem := range problems {
fmt.Print(problem.statement, " ")
guess, _ := r.ReadString('\n')
// The delimiter is recorded with the data, so it should be removed
// in order to ensure proper comparisons to what the user had in mind
if strings.TrimRight(guess, "\n") == problem.answer {
right++
}
}
fmt.Println("\nCorrect: ", right)
fmt.Println("Total: ", len(problems))
fmt.Print("\nQUIZ END\n\n")
}
func readFromFile(filename string) []problem {
cf, eo := os.Open(filename)
if eo != nil {
log.Fatal("Error: ", eo)
}
cr := csv.NewReader(cf)
// The csv config file should have exactly 2 fields for all records-
// anything else is considerd a corruption and is treated as a fatal error.
cr.FieldsPerRecord = 2
var ps []problem
for {
// Get a string slice from each column
record, err := cr.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal("Error: ", err)
}
ps = append(ps, newProb(record))
}
return ps
}
func newProb(r []string) problem {
return problem{statement: r[0], answer: strings.TrimRight(r[1], "\r\n")}
}