go交互输入

2021-07-06  本文已影响0人  sjyu_eadd
package main

import (
    "bufio"
    "bytes"
    "fmt"
    "os"
    "strings"
)

func main() {
    fmt.Print("Please input:")
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Scan()
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "error:", err)
    }
    fmt.Printf("bufio.NewScanner:%q\r\n", scanner.Text())
    //--------------------------------------------------------------

    fmt.Print("Please input:")
    inputBytes := make([]byte, 512)
    _, err := os.Stdin.Read(inputBytes)
    if err != nil {
        fmt.Println("read error:", err)
    }
    textBytes := bytes.TrimRight(inputBytes, "\x00")
    fmt.Printf("os.Stdin.Read: %q\r\n", strings.TrimSpace(string(textBytes)))

    //-------------------------------------------------------------------
    fmt.Print("Please input:")
    inputText := ""
    fmt.Scanf("%s", &inputText)   //注意此方法在win下会因为\r\n读取两次
    fmt.Printf("fmt.Scanf: %q\r\n", inputText)

    //-------------------------------------------------------------------
    fmt.Print("Please input:")
    inputText2 := ""
    stdin := bufio.NewReader(os.Stdin)
    fmt.Fscan(stdin, &inputText2)
    fmt.Printf("fmt.Scanf: %q\r\n", inputText2)

    //-------------------------------------------------------------------
    inputReader := bufio.NewReader(os.Stdin)
    fmt.Printf("Please input:")
    input, err := inputReader.ReadString('\n')
    if err != nil {
        fmt.Println("There were errors reading, exiting program.")
        return
    }
    fmt.Printf("Your input is %s", input)

}
上一篇下一篇

猜你喜欢

热点阅读