blob: 3da914142194895ea37e660c621d3835fb251a86 [file] [log] [blame]
Rob Pikedbd409a2013-02-21 15:55:40 -08001// 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.
4
5package bufio_test
6
7import (
8 "bufio"
9 "fmt"
10 "os"
11 "strconv"
12 "strings"
13)
14
Andrew Gerrand8eb8ad22013-08-12 13:03:50 +100015func 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!
21}
22
Rob Pikedbd409a2013-02-21 15:55:40 -080023// The simplest use of a Scanner, to read standard input as a set of lines.
24func ExampleScanner_lines() {
25 scanner := bufio.NewScanner(os.Stdin)
26 for scanner.Scan() {
27 fmt.Println(scanner.Text()) // Println will add back the final '\n'
28 }
29 if err := scanner.Err(); err != nil {
Rob Pike5bbdf402013-03-21 14:56:42 -070030 fmt.Fprintln(os.Stderr, "reading standard input:", err)
Rob Pikedbd409a2013-02-21 15:55:40 -080031 }
32}
33
34// Use a Scanner to implement a simple word-count utility by scanning the
35// input as a sequence of space-delimited tokens.
36func 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)
42 // Count the words.
43 count := 0
44 for scanner.Scan() {
45 count++
46 }
47 if err := scanner.Err(); err != nil {
Rob Pike5bbdf402013-03-21 14:56:42 -070048 fmt.Fprintln(os.Stderr, "reading input:", err)
Rob Pikedbd409a2013-02-21 15:55:40 -080049 }
50 fmt.Printf("%d\n", count)
51 // Output: 15
52}
53
54// Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
55// 32-bit decimal input.
56func 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)
65 }
66 return
67 }
68 // Set the split function for the scanning operation.
69 scanner.Split(split)
70 // Validate the input
71 for scanner.Scan() {
72 fmt.Printf("%s\n", scanner.Text())
73 }
74
75 if err := scanner.Err(); err != nil {
76 fmt.Printf("Invalid input: %s", err)
77 }
78 // Output:
79 // 1234
80 // 5678
81 // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
82}