I
I
Ivan2019-07-17 14:02:46
go
Ivan, 2019-07-17 14:02:46

When confirming the exit through the console, the last Scan is triggered, how to fix it?

I am writing a Quiz console application (test) in a loop displaying questions and possible answers, I need to implement a feature if the user tries to close the application using Ctrl + C, you need to ask for confirmation . When confirming the exit through the console, the last Scan is triggered, which is waiting for an answer option, i.e. . Really Quit? [y/n] I enter y - and it accepts it as the answer to the last Scan (in which the answer to the next test question was expected). I omitted the formation of questions for compactness.

package main

import (
  "fmt"
  "strconv"
  //"bufio"
  "os"
  "syscall"
  "os/signal"
  //"runtime"
)

func main() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT) //os.Interrupt
go func() {
  for {
    select {
    case <-c:
      fmt.Printf("\nReally quit? [y/n] > ")
      var choice string
      fmt.Scan(&choice)

      if choice == "y" {
        os.Exit(0)
      }
    }
  }
}()
        fmt.Println("hello")
    
    var text string
    //k:
    for {
      fmt.Println("What ...?")  
      fmt.Scan(&text)//сканим ответ юзера
      inp, err := strconv.Atoi(text)
      if err != nil {
        fmt.Println(text, "Invalid number for exit!")
        //goto k
      } else {
        fmt.Println(inp)
        os.Exit(0)
      }
    }

}

Also tried to read through
var reader = bufio.NewReader(os.Stdin)
func myScan() string {   
    text, _ := reader.ReadString('\n')
    return text
}

The result is the same

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2019-07-17
@uvelichitel

func readInput() string{
  //fmt.Scan()
  //process error
}
func main() {
  c := make(chan os.Signal, 1)
  signal.Notify(c, syscall.SIGINT) //os.Interrupt
  for {
    select {
        case <-c:
          choice:=readInput()
          //process choice
        default:
          text:=readInput()
          //process input text
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question