github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/bufio/example_test.go (about)

     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.
     4  
     5  package bufio_test
     6  
     7  import (
     8  	"bufio"
     9  	"fmt"
    10  	"os"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  // The simplest use of a Scanner, to read standard input as a set of lines.
    16  func ExampleScanner_lines() {
    17  	scanner := bufio.NewScanner(os.Stdin)
    18  	for scanner.Scan() {
    19  		fmt.Println(scanner.Text()) // Println will add back the final '\n'
    20  	}
    21  	if err := scanner.Err(); err != nil {
    22  		fmt.Fprintln(os.Stderr, "reading standard input:", err)
    23  	}
    24  }
    25  
    26  // Use a Scanner to implement a simple word-count utility by scanning the
    27  // input as a sequence of space-delimited tokens.
    28  func ExampleScanner_words() {
    29  	// An artificial input source.
    30  	const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
    31  	scanner := bufio.NewScanner(strings.NewReader(input))
    32  	// Set the split function for the scanning operation.
    33  	scanner.Split(bufio.ScanWords)
    34  	// Count the words.
    35  	count := 0
    36  	for scanner.Scan() {
    37  		count++
    38  	}
    39  	if err := scanner.Err(); err != nil {
    40  		fmt.Fprintln(os.Stderr, "reading input:", err)
    41  	}
    42  	fmt.Printf("%d\n", count)
    43  	// Output: 15
    44  }
    45  
    46  // Use a Scanner with a custom split function (built by wrapping ScanWords) to validate
    47  // 32-bit decimal input.
    48  func ExampleScanner_custom() {
    49  	// An artificial input source.
    50  	const input = "1234 5678 1234567901234567890"
    51  	scanner := bufio.NewScanner(strings.NewReader(input))
    52  	// Create a custom split function by wrapping the existing ScanWords function.
    53  	split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
    54  		advance, token, err = bufio.ScanWords(data, atEOF)
    55  		if err == nil && token != nil {
    56  			_, err = strconv.ParseInt(string(token), 10, 32)
    57  		}
    58  		return
    59  	}
    60  	// Set the split function for the scanning operation.
    61  	scanner.Split(split)
    62  	// Validate the input
    63  	for scanner.Scan() {
    64  		fmt.Printf("%s\n", scanner.Text())
    65  	}
    66  
    67  	if err := scanner.Err(); err != nil {
    68  		fmt.Printf("Invalid input: %s", err)
    69  	}
    70  	// Output:
    71  	// 1234
    72  	// 5678
    73  	// Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range
    74  }