...
Source file
src/bufio/example_test.go
Documentation: bufio
1
2
3
4
5 package bufio_test
6
7 import (
8 "bufio"
9 "fmt"
10 "os"
11 "strconv"
12 "strings"
13 )
14
15 func ExampleWriter() {
16 w := bufio.NewWriter(os.Stdout)
17 fmt.Fprint(w, "Hello, ")
18 fmt.Fprint(w, "world!")
19 w.Flush()
20
21 }
22
23
24 func ExampleScanner_lines() {
25 scanner := bufio.NewScanner(os.Stdin)
26 for scanner.Scan() {
27 fmt.Println(scanner.Text())
28 }
29 if err := scanner.Err(); err != nil {
30 fmt.Fprintln(os.Stderr, "reading standard input:", err)
31 }
32 }
33
34
35 func ExampleScanner_Bytes() {
36 scanner := bufio.NewScanner(strings.NewReader("gopher"))
37 for scanner.Scan() {
38 fmt.Println(len(scanner.Bytes()) == 6)
39 }
40 if err := scanner.Err(); err != nil {
41 fmt.Fprintln(os.Stderr, "shouldn't see an error scanning a string")
42 }
43
44
45 }
46
47
48
49 func ExampleScanner_words() {
50
51 const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
52 scanner := bufio.NewScanner(strings.NewReader(input))
53
54 scanner.Split(bufio.ScanWords)
55
56 count := 0
57 for scanner.Scan() {
58 count++
59 }
60 if err := scanner.Err(); err != nil {
61 fmt.Fprintln(os.Stderr, "reading input:", err)
62 }
63 fmt.Printf("%d\n", count)
64
65 }
66
67
68
69 func ExampleScanner_custom() {
70
71 const input = "1234 5678 1234567901234567890"
72 scanner := bufio.NewScanner(strings.NewReader(input))
73
74 split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
75 advance, token, err = bufio.ScanWords(data, atEOF)
76 if err == nil && token != nil {
77 _, err = strconv.ParseInt(string(token), 10, 32)
78 }
79 return
80 }
81
82 scanner.Split(split)
83
84 for scanner.Scan() {
85 fmt.Printf("%s\n", scanner.Text())
86 }
87
88 if err := scanner.Err(); err != nil {
89 fmt.Printf("Invalid input: %s", err)
90 }
91
92
93
94
95 }
96
97
98
99 func ExampleScanner_emptyFinalToken() {
100
101 const input = "1,2,3,4,"
102 scanner := bufio.NewScanner(strings.NewReader(input))
103
104 onComma := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
105 for i := 0; i < len(data); i++ {
106 if data[i] == ',' {
107 return i + 1, data[:i], nil
108 }
109 }
110 if !atEOF {
111 return 0, nil, nil
112 }
113
114
115
116 return 0, data, bufio.ErrFinalToken
117 }
118 scanner.Split(onComma)
119
120 for scanner.Scan() {
121 fmt.Printf("%q ", scanner.Text())
122 }
123 if err := scanner.Err(); err != nil {
124 fmt.Fprintln(os.Stderr, "reading input:", err)
125 }
126
127 }
128
View as plain text