Terminal to read and write
Constants related file handle operation terminal
os.Stdin // standard input os.Stdout // standard output (output to the terminal) os.Stderr // standard error output (output to the terminal)
fmt common usage
fmt.Scanln (firstName &, & lastName) // read character string from the terminal (space separated) fmt.Scanf ( " % S% S " , & firstName, & lastName) // action with fmt.Scanln (), but fmt.Scanf () reads a string can be read both digital fmt.Printf ( " the Hi S% S%! \ n- " , firstName, lastName) // format output fmt.Sscanf (input, format, & f , & i, & s ) // the format string is read (first parameter represents a string to be read, the second parameter read format, the latter parameter represents a variable which is assigned)
Sample code:
package main import "fmt" type Student struct{ Name string Age int Score float64 } func main(){ var s = "stu01 age is 18 score is 95.5" var stu Student fmt.Sscanf(s,"%s age is %d score is %f",&stu.Name,&stu.Age,&stu.Score) // 变量要传入地址 fmt.Println(stu) } // 运行结果: [root@NEO example01_Sscanf]# go run main/main.go {stu01 18 95.5} [root@NEO example01_Sscanf]#
With write buffer:
The sample code :( reads from the standard input )
main Package Penalty for Import ( " bufio " " os " " fmt " ) FUNC main () { Reader: = bufio.NewReader (os.Stdin) // Go the struct has no constructor, so bufio package to write a constructor NewReader , a back pointer Reader implemented; bufio.NewReader () need to pass a io.Reader interface that has aspirated a Read () method, but also to achieve os.Stdin Read () method, i.e. realized io.Reader this interface fmt.Println ( " PLS INPUT: " ) STR, ERR: = reader.ReadString ( ' \ n- ' ) // read buffer zone; a parameter () is a byte in ReadString separator, so with the single primer IF ERR! = nil { FMT.Println("read string failed:",err) return } fmt.Printf("read string success,str: %s\n",str) } // 运行结果: [root@NEO example02_bufio01]# go run main/main.go pls input: i am neo read string success,str: i am neo [root@NEO example02_bufio01]#