bufio
Posted chenguifeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了bufio相关的知识,希望对你有一定的参考价值。
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 ", 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, Made glorious summer by this sun of York. " 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 ", count) 25 }
以上是关于bufio的主要内容,如果未能解决你的问题,请参考以下文章