Created
January 28, 2018 14:40
-
-
Save jtslear/73da61829f6141c318dd3545dbed46ee to your computer and use it in GitHub Desktop.
Part 2 for Quiz Gophercise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/csv" | |
"flag" | |
"fmt" | |
"os" | |
"strings" | |
"time" | |
) | |
func main() { | |
var input = flag.String("input", "problems.csv", "CSV deliminited file, format: 'problem,answer'") | |
var timeLimit = flag.Int("timeLimit", 30, "Time limit to answer each question.") | |
flag.Parse() | |
file, err := os.Open(*input) | |
if err != nil { | |
fmt.Printf("Error reading file: %s\n", err) | |
} | |
csv := csv.NewReader(file) | |
q, err := csv.ReadAll() | |
if err != nil { | |
fmt.Printf("Error reading csv record: %s\n", err) | |
} | |
fmt.Printf("You'll have %d seconds between each question. Press enter when ready.", *timeLimit) | |
fmt.Scanf("\n") | |
var correct int | |
for i := 0; i < len(q); i++ { | |
fmt.Printf("Question: %v: ", q[i][0]) | |
answerChannel := make(chan string) | |
go func() { | |
var userInput string | |
fmt.Scanf("%s\n", &userInput) | |
cleanInput := strings.TrimSpace(userInput) | |
answerChannel <- cleanInput | |
}() | |
select { | |
case cleanInput := <-answerChannel: | |
if cleanInput == q[i][1] { | |
fmt.Printf("Correct!\n") | |
correct++ | |
} else { | |
fmt.Printf("%v is incorrect, the answer is %v\n", cleanInput, q[i][1]) | |
} | |
case <-time.After(time.Duration(*timeLimit) * time.Second): | |
fmt.Printf("Times up! The answer is %v\n", q[i][1]) | |
} | |
} | |
fmt.Printf("You answered %d correctly out of %d\n", correct, len(q)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment