Skip to content

Instantly share code, notes, and snippets.

@adilw3nomad
Last active June 22, 2019 18:40
Show Gist options
  • Save adilw3nomad/4775ff240fea61eaed7a1cf524279db2 to your computer and use it in GitHub Desktop.
Save adilw3nomad/4775ff240fea61eaed7a1cf524279db2 to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"encoding/csv"
"fmt"
"io"
"log"
"os"
"strings"
)
type quizItem struct {
question string
answer string
}
func main() {
csvFile, err := os.Open("problems.csv")
if err != nil {
log.Fatal(err)
}
defer csvFile.Close()
reader := csv.NewReader(csvFile)
// Create an infinite loop to go through entire file
for {
// Read a single line
record, err := reader.Read()
// Stop the loop if we reach the end of the file
// Else log any other error except nil
if err != nil {
if err == io.EOF {
break
}
log.Fatal(err)
}
// Create quiz item from record
quizItem := quizItem{
question: record[0],
answer: record[1],
}
// Print out the question.
fmt.Println("Question: ", quizItem.question)
// Create reader and allow user to input their answer.
inputReader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your answer now: ")
// Expect answer to be given once they hit return.
text, err := inputReader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
fmt.Println("Your answer is:", text)
// Trim the newline suffix from the input.
text = strings.TrimSuffix(text, "\n")
// Compare the answer given by the user to the correct answer
// Print a response accordingly.
if text == quizItem.answer {
fmt.Println("Correct!")
} else {
fmt.Println("WRONG! Answer is: ", quizItem.answer)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment