码迷,mamicode.com
首页 > 其他好文 > 详细

bufio

时间:2019-12-10 13:07:19      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:ack   %s   function   data   reader   byte   flush   main   set   

 1 package main
 2 
 3 import (
 4     "bufio"
 5     "fmt"
 6     "os"
 7 )
 8 
 9 func main() {
10     w := bufio.NewWriter(os.Stdout)
11     fmt.Fprint(w, "Hello, ")
12     fmt.Fprint(w, "world!")
13     w.Flush() // Don‘t forget to flush!
14 }
 1 package main
 2 
 3 import (
 4     "bufio"
 5     "fmt"
 6     "strconv"
 7     "strings"
 8 )
 9 
10 func main() {
11     // An artificial input source.
12     const input = "1234 5678 1234567901234567890"
13     scanner := bufio.NewScanner(strings.NewReader(input))
14     // Create a custom split function by wrapping the existing ScanWords function.
15     split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
16         advance, token, err = bufio.ScanWords(data, atEOF)
17         if err == nil && token != nil {
18             _, err = strconv.ParseInt(string(token), 10, 32)
19         }
20         return
21     }
22     // Set the split function for the scanning operation.
23     scanner.Split(split)
24     // Validate the input
25     for scanner.Scan() {
26         fmt.Printf("%s\n", scanner.Text())
27     }
28     if err := scanner.Err(); err != nil {
29         fmt.Printf("Invalid input: %s", err)
30     }
31 }
 1 package main
 2 
 3 import (
 4     "bufio"
 5     "fmt"
 6     "os"
 7 )
 8 
 9 func main() {
10     scanner := bufio.NewScanner(os.Stdin)
11     for scanner.Scan() {
12         fmt.Println("input: ", scanner.Text())
13     }
14     if err := scanner.Err(); err != nil {
15         fmt.Fprintln(os.Stderr, "reading standard input: ", err)
16     }
17 }
 1 package main
 2 
 3 import (
 4     "bufio"
 5     "fmt"
 6     "os"
 7     "strings"
 8 )
 9 
10 func main() {
11     // An artificial input source.
12     const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n"
13     scanner := bufio.NewScanner(strings.NewReader(input))
14     // Set the split function for the scanning operation.
15     scanner.Split(bufio.ScanWords)
16     // Count the words.
17     count := 0
18     for scanner.Scan() {
19         count++
20     }
21     if err := scanner.Err(); err != nil {
22         fmt.Fprintln(os.Stderr, "reading input:", err)
23     }
24     fmt.Printf("%d\n", count)
25 }

 

bufio

标签:ack   %s   function   data   reader   byte   flush   main   set   

原文地址:https://www.cnblogs.com/chenguifeng/p/12015792.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!