1. 標准輸入輸出
os提供了標准輸入輸出:
Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
func NewFile(fd uintptr, name string) *File
2. Scan
從鍵盤和標准輸入os.Stdin讀取輸入,最簡單的方法是使用fmt包提供的Scan和Sscan開頭的函數。
func Scan(a ...interface{}) (n int, err error) func Scanf(format string, a ...interface{}) (n int, err error) func Scanln(a ...interface{}) (n int, err error) func Sscan(str string, a ...interface{}) (n int, err error) func Sscanf(str string, format string, a ...interface{}) (n int, err error) func Sscanln(str string, a ...interface{}) (n int, err error) func Fscan(r io.Reader, a ...interface{}) (n int, err error) func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error) func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
Scanln 掃描來自標准輸入的文本,將空格分隔的值依次存放到后續的參數內,直到碰到換行。
Scanf的第一個參數是格式串,其他都相同。
Sscan及開頭的函數輸入變成了string,Fscan及開頭的函數輸入變成了io.Reader。
Scan, Fscan, Sscan treat newlines in the input as spaces.
Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.
fmt.Println("Please enter your full name: ") fmt.Scanln(&firstName, &lastName) fmt.Printf("Hi %s %s!\n", firstName, lastName) fmt.Sscanf("30.0 * 25 * hello", "%f * %d * %s", &f, &i, &s) fmt.Println("From the string we read: ", f, i, s) fmt.Println("Please enter string: ") fmt.Scan(&s) fmt.Println(s)
3. Fprintf
printf相關:
func Fprint(w io.Writer, a ...interface{}) (n int, err error) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
通過Fprintln()寫文件
const name, age = "Kim", 22 n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.") // The n and err return values from Fprintln are // those returned by the underlying io.Writer. if err != nil { fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err) } 或 for _, v := range d { fmt.Fprintln(f, v) if err != nil { fmt.Println(err) return } }
參考:
1. https://golang.google.cn/pkg/fmt/#Scanln