fmt
When read from stdin or write to stdout, the easiest way is to use the fmt
package method. Just like c.
import "fmt"
var t int
//Read
fmt.Scanf("%d", &t)
//Write
fmt.Println(t)
Limitation
But fmt is very slow if you want to read a lot of data from the stdin or write to stdout. In this situation, we can use the bufio
instead.
Bufio
Scanner
For the bufio, one way is to use the Scanner.
import (
"fmt"
"os"
"bufio"
"strconv"
)
var sc = bufio.NewScanner(os.Stdin)
func main() {
sc.Split(bufio.ScanWords)
sc.Scan()
t := strconv.ParseInt(sc.Text(), 10, 64)
for t > 0 {
t--
sc.Scan()
v, _ := strconv.ParseInt(sc.Text(), 10, 64)
fmt.Println(n - i + 1)
}
}
Limitation
The buffer size is not very large. Just 64 * 1024
according to the go lang doc.
If you read a word that is very long such as 10000000, it will return a empty string.
To solve this, we can use the Reader
to custom the buffer size or read more times from the buffer to get a very long string.
Reader
package main
import (
"bufio"
"os"
"strconv"
"strings"
)
const N int = 1000005
var lbr = bufio.NewReaderSize(os.Stdin, N)
var lbw = bufio.NewWriterSize(os.Stdout, N)
//If the line is less then the buffer
func readline() string {
buf, _, _ := lbr.ReadLine()
return string(buf)
}
//If the line over the buffer
func read_buf_over_line() string {
var buf []byte
for {
bytes, more, _ := lbr.ReadLine()
buf = append(buf, bytes...)
if !more { break }
}
return string(buf)
}
func main() {
str := readline()
m, _ := strconv.Atoi(readline())
for q := 0; q < m; q++ {
qs := strings.Split(readline(), " ")
lbw.WriteString("Something...\n")
}
lbw.Flush()
}