1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
15 func ExampleWriter() {
16 w
:= bufio
.NewWriter(os
.Stdout
)
17 fmt
.Fprint(w
, "Hello, ")
18 fmt
.Fprint(w
, "world!")
19 w
.Flush() // Don't forget to flush!
20 // Output: Hello, world!
23 // The simplest use of a Scanner, to read standard input as a set of lines.
24 func ExampleScanner_lines() {
25 scanner
:= bufio
.NewScanner(os
.Stdin
)
27 fmt
.Println(scanner
.Text()) // Println will add back the final '\n'
29 if err
:= scanner
.Err(); err
!= nil {
30 fmt
.Fprintln(os
.Stderr
, "reading standard input:", err
)
34 // Use a Scanner to implement a simple word-count utility by scanning the
35 // input as a sequence of space-delimited tokens.
36 func ExampleScanner_words() {
37 // An artificial input source.
38 const input
= "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
39 scanner
:= bufio
.NewScanner(strings
.NewReader(input
))
40 // Set the split function for the scanning operation.
41 scanner
.Split(bufio
.ScanWords
)
47 if err
:= scanner
.Err(); err
!= nil {
48 fmt
.Fprintln(os
.Stderr
, "reading input:", err
)
50 fmt
.Printf("%d\n", count
)
54 // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
55 // 32-bit decimal input.
56 func ExampleScanner_custom() {
57 // An artificial input source.
58 const input
= "1234 5678 1234567901234567890"
59 scanner
:= bufio
.NewScanner(strings
.NewReader(input
))
60 // Create a custom split function by wrapping the existing ScanWords function.
61 split
:= func(data
[]byte, atEOF
bool) (advance
int, token
[]byte, err error
) {
62 advance
, token
, err
= bufio
.ScanWords(data
, atEOF
)
63 if err
== nil && token
!= nil {
64 _
, err
= strconv
.ParseInt(string(token
), 10, 32)
68 // Set the split function for the scanning operation.
72 fmt
.Printf("%s\n", scanner
.Text())
75 if err
:= scanner
.Err(); err
!= nil {
76 fmt
.Printf("Invalid input: %s", err
)
81 // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range