39 lines
754 B
Go
39 lines
754 B
Go
|
// Package keyboard reads user input from the keyboard.
|
||
|
package keyboard
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"os"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// GetString reads a string from the keyboard.
|
||
|
// It returns the string read and any error encountered.
|
||
|
func GetString() (string, error) {
|
||
|
reader := bufio.NewReader(os.Stdin)
|
||
|
input, err := reader.ReadString('\n')
|
||
|
if err != nil {
|
||
|
return "", err
|
||
|
}
|
||
|
|
||
|
return input, nil
|
||
|
}
|
||
|
|
||
|
// GetFloat reads a floating-point number from the keyboard.
|
||
|
// It returns the number read and any error encountered.
|
||
|
func GetFloat() (float64, error) {
|
||
|
input, err := GetString()
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
input = strings.TrimSpace(input)
|
||
|
number, err := strconv.ParseFloat(input, 64)
|
||
|
if err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
|
||
|
return number, nil
|
||
|
}
|