美文网首页
go交互输入

go交互输入

作者: sjyu_eadd | 来源:发表于2021-07-06 14:46 被阅读0次
    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)
    
    }
    

    相关文章

      网友评论

          本文标题:go交互输入

          本文链接:https://www.haomeiwen.com/subject/wpsgultx.html