Home > Enterprise >  Default value assigned when pressing Enter
Default value assigned when pressing Enter

Time:03-22

I want a default value to be assigned when pressing Enter without giving one.

From my experience Go Playground doesn't handle fmt.Scan inputs, so I quote the code here:
(If it's possible, tell me how please!)

package main

import (
    "fmt"
    "time"
)

func main() {
    t := 0
    fmt.Print("seconds? ")
    fmt.Scan(&t)
    time.Sleep(time.Duration(t) * time.Second)
    fmt.Println("in", t)
}

I've initialized the value of t to 0 but when I press Enter without giving a value the program waits until I give some value. I'm not interested in error checking (if that's possible). I just want the code to accept a single Enter press, as 0 Enter.

CodePudding user response:

Simply use fmt.Scanln() instead of fmt.Scan():

fmt.Scanln(&t)

Quoting from fmt.Scanln():

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

On the other hand, fmt.Scan() does not stop at a newline, but:

Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.

In general I suggest to use bufio.Scanner to read input by lines, and do whatever you want to with the lines (check if its empty, or parse it the way you want). bufio.NewScanner() allows you to use a (predefined) string as the source (combined with strings.NewReader()–for easy testing) or pass os.Stdin if you want to read user input.

CodePudding user response:

You can use bufio.Reader

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
    "time"
)

func main() {
    var t int

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("seconds? ")
    for {
        tStr, err := reader.ReadString('\n')
        tStr = strings.TrimSpace(tStr)

        t, err = strconv.Atoi(tStr)
        if err != nil {
            fmt.Println("invalid input, please write a number")
            continue
        }
        break
    }

    time.Sleep(time.Duration(t) * time.Second)
    fmt.Println("in", t)
}
  • Related