Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions students/kannanenator/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package main

import "os"
import "fmt"
import "log"
import "flag"
import "time"
import "encoding/csv"
import "bufio"
import "strings"

func main() {

filenamePtr := flag.String("filename", "problems.csv", "file containing the set of problems")
limitPtr := flag.Int("limit", 30, "quiz time limit")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would add a check based on the NArg func in the flag pkg to handle the case where I try to run the game with no flags.

flag.Parse()

file, err := os.Open(*filenamePtr)
handleError(err)
defer file.Close()

csvReader := csv.NewReader(file)
rows, err := csvReader.ReadAll()
handleError(err)

numQs := len(rows)
numCorrect := 0

timer := time.NewTimer(time.Second * time.Duration(*limitPtr))
go func() {
<- timer.C
// when the timer ends, we kill the quiz
fmt.Println("\nTime is up")
os.Exit(0)
}()

consoleReader := bufio.NewReader(os.Stdin)
for idx, element := range rows {
q, a := element[0], element[1]
fmt.Print("Problem #", idx+1 ,": ", q, " = ")
input, _ := consoleReader.ReadString('\n')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping error values is a code smell, so unless your specific case calls for it, don't do it!


// compare w/o whitespace
if strings.TrimSpace(input) == strings.TrimSpace(a) {
numCorrect++
}
}

fmt.Println("You got", numCorrect, "out of", numQs, "correct")
}

func handleError(err error){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my opinion, this kind of general error helper func is discouraged. While more verbose, we always prefer explicit handling at the call site. So instead of handleError, in each case where you get an error value, I would opt for using

log.Fatalf("could not open file: %v\n", err)

or

// if you want to print to stderr and trigger an unsuccessful exit, for example
fmt.Fprintf(os.Stderr, "could not read input string: %v\n", err)
os.Exit(1)

if err != nil {
log.Fatal(err)
}
}