-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathscanUsingBufio.go
70 lines (56 loc) · 1.17 KB
/
scanUsingBufio.go
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Print(`Which example do you want to run?
1) fmt.Scan(...)
2) bufio.Reader.ReadString(...)
Please enter 1 or 2 and press ENTER: `)
reader := bufio.NewReader(os.Stdin)
result, _, err := reader.ReadRune()
if err != nil {
fmt.Println(err)
return
}
switch result {
case '1':
runScan()
break
case '2':
runReadString()
break
default:
return
}
}
func runScan() {
// You must declare a variable and then pass the pointer into Scan() function below
var input string
fmt.Print("\nPlease insert a string and press ENTER: ")
// Using the fmt.Scan function, we can read single words as an ASCII string
num, err := fmt.Scan(&input)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(input)
fmt.Println(num)
}
const INPUTDELIMITER = '\n'
func runReadString() {
fmt.Print("\nPlease insert a string and press ENTER: ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString(INPUTDELIMITER)
if err != nil {
fmt.Println(err)
return
}
// Convert CRLF to LF
input = strings.Replace(input, "\n", "", -1)
fmt.Println(input)
fmt.Println("Exiting program.")
}