-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgonsole.go
More file actions
55 lines (43 loc) · 1006 Bytes
/
gonsole.go
File metadata and controls
55 lines (43 loc) · 1006 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package gonsole
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Gonsole struct {
reader *bufio.Reader
}
func New() *Gonsole {
gon := &Gonsole{}
// setting standard input source for reader
gon.SetSource(os.Stdin)
return gon
}
// Set custom input source (this separate method is mainly here for testing purposes)
func (gon *Gonsole) SetSource(input *os.File) {
gon.reader = bufio.NewReader(input)
}
// Asks user to enter a valid integer value until he enters correct value.
func (gon *Gonsole) ReadInt(msg string) int {
var readSuccess bool = false
var inputInt int
var errConv error
for readSuccess == false {
fmt.Printf("%s", msg)
inputStr, err := gon.reader.ReadString('\n')
if err != nil {
fmt.Printf("Reading Error: %v\n", err)
continue
}
inputStr = strings.TrimSpace(inputStr)
inputInt, errConv = strconv.Atoi(inputStr)
if errConv != nil {
fmt.Printf("Converting Error: %v\n", errConv)
continue
}
readSuccess = true
}
return inputInt
}