Skip to content

Instantly share code, notes, and snippets.

@lalizita
Last active March 14, 2022 21:16
Show Gist options
  • Save lalizita/4feb75af8885b0c918b5a7f942f2cdf0 to your computer and use it in GitHub Desktop.
Save lalizita/4feb75af8885b0c918b5a7f942f2cdf0 to your computer and use it in GitHub Desktop.
Reading a csv file with go lang, csv file is in https://gist.github.com/lalizita/84daf831c49191d226c29e44097ec1f5
package main
import (
"encoding/csv"
"fmt"
"io"
"log"
"os"
)
type QuizQuestion struct {
Question string
Result string
Answer string
}
func main() {
f, err := os.Open("file.csv")
if err != nil {
log.Fatal("Opening file:", err)
}
c := csv.NewReader(f)
r, err := c.ReadAll()
if err != nil {
log.Fatal("Erro ao retornar CSV:", err)
}
if err == io.EOF {
log.Fatal("CSV vazio")
}
allQuestions := make([]QuizQuestion, 0)
for _, r := range r {
allQuestions = append(allQuestions, QuizQuestion{Question: r[0], Result: r[1]})
}
totalCorrect := 0
for index, q := range allQuestions {
fmt.Printf("Questão %d - %s\n", index+1, q.Question)
fmt.Scan(&allQuestions[index].Answer)
if allQuestions[index].Answer == allQuestions[index].Result {
totalCorrect++
}
}
fmt.Println("TOTAL DE QUESTÕES: ", len(allQuestions))
fmt.Println("===================")
fmt.Println("CERTAS: ", totalCorrect)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment