Last active
March 14, 2022 21:16
-
-
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
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" | |
"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