Skip to content

Trying to Set a Timer For Individual Question #136

@Pranay-ai

Description

@Pranay-ai

package main

import (
"encoding/csv"
"flag"
"fmt"
"os"
"time"
)

func main() {
// Parse CSV file name from command-line arguments
csvFileName := flag.String("csv", "problems.csv", "a csv file in the format of 'question,answer'")
flag.Parse()

// Open the CSV file
file, err := os.Open(*csvFileName)
if err != nil {
	fmt.Println("Failed to open the CSV file:", *csvFileName)
	os.Exit(1)
}
defer file.Close()

// Read the CSV file
r := csv.NewReader(file)
lines, err := r.ReadAll()
if err != nil {
	fmt.Println("Failed to parse the provided CSV file.")
	os.Exit(1)
}
problems := parseLines(lines)

correctAnswerCount := 0
timeLimit := 5 * time.Second

for i, p := range problems {
	fmt.Printf("Problem %d: %s = \n", i+1, p.question)

	// Create a timer for the current question
	timer := time.NewTimer(timeLimit)

	// Create a channel for the answer
	answerChannel := make(chan string)

	// Launch a goroutine to read user input
	go func() {
		var answer string
		fmt.Scanln(&answer)
		answerChannel <- answer
	}()

	select {
	case <-timer.C:
		fmt.Println("Time's up! Moving to the next question.")
	case answer := <-answerChannel:
		if answer == p.answer {
			correctAnswerCount++
		}
		timer.Stop() // Stop the timer when answer is received
	}
}

// Print the final score
fmt.Printf("You scored %d out of %d\n", correctAnswerCount, len(problems))

}

// Problem struct for each question-answer pair
type problem struct {
question string
answer string
}

// parseLines parses lines from CSV to a slice of problem structs
func parseLines(lines [][]string) []problem {
ret := make([]problem, len(lines))
for i, line := range lines {
ret[i] = problem{
question: line[0],
answer: line[1],
}
}
return ret
}

I Have been trying to Set a timer For Each Individual Question But Problem is When the Timer is expired the old "Scanln" function is still waiting for the input, Is their any way we can solve this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions