How to read from standard input in the console?

后端 未结 11 1122
迷失自我
迷失自我 2020-11-28 00:54

I would like to read standard input from the command line, but my attempts have ended with the program exiting before I\'m prompted for input. I\'m looking for the equivalen

相关标签:
11条回答
  • 2020-11-28 01:26

    I'm late to the party. But how about one liner:

    data, err := ioutil.ReadAll(os.Stdin)
    

    and press ctrl+d (EOT) once input is entered on command line.

    0 讨论(0)
  • 2020-11-28 01:29

    Cleanly read in a couple prompted values:

    // Create a single reader which can be called multiple times
    reader := bufio.NewReader(os.Stdin)
    // Prompt and read
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Print("Enter More text: ")
    text2, _ := reader.ReadString('\n')
    // Trim whitespace and print
    fmt.Printf("Text1: \"%s\", Text2: \"%s\"\n",
        strings.TrimSpace(text), strings.TrimSpace(text2))
    

    Here's a run:

    Enter text: Jim
    Enter More text: Susie
    Text1: "Jim", Text2: "Susie"
    
    0 讨论(0)
  • 2020-11-28 01:30

    you can as well try:

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }
    
    if scanner.Err() != nil {
        // handle error.
    }
    
    0 讨论(0)
  • 2020-11-28 01:30

    I think a more standard way to do this would be:

    package main
    
    import "fmt"
    
    func main() {
        fmt.Print("Enter text: ")
        var input string
        fmt.Scanln(&input)
        fmt.Print(input)
    }
    

    Take a look at the scan godoc: http://godoc.org/fmt#Scan

    Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.

    Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

    0 讨论(0)
  • 2020-11-28 01:31

    Always try to use the bufio.NewScanner for collecting input from the console. As others mentioned, there are multiple ways to do the job but Scanner is originally intended to do the job. Dave Cheney explains why you should use Scanner instead of bufio.Reader's ReadLine.

    https://twitter.com/davecheney/status/604837853344989184?lang=en

    Here is the code snippet answer for your question

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
    )
    
    /*
     Three ways of taking input
       1. fmt.Scanln(&input)
       2. reader.ReadString()
       3. scanner.Scan()
    
       Here we recommend using bufio.NewScanner
    */
    
    func main() {
        // To create dynamic array
        arr := make([]string, 0)
        scanner := bufio.NewScanner(os.Stdin)
        for {
            fmt.Print("Enter Text: ")
            // Scans a line from Stdin(Console)
            scanner.Scan()
            // Holds the string that scanned
            text := scanner.Text()
            if len(text) != 0 {
                fmt.Println(text)
                arr = append(arr, text)
            } else {
                break
            }
    
        }
        // Use collected inputs
        fmt.Println(arr)
    }
    

    If you don't want to programmatically collect the inputs, just add these lines

       scanner := bufio.NewScanner(os.Stdin)
       scanner.Scan()
       text := scanner.Text()
       fmt.Println(text)
    

    The output of above program will be:

    Enter Text: Bob
    Bob
    Enter Text: Alice
    Alice
    Enter Text:
    [Bob Alice]
    

    Above program collects the user input and saves them to an array. We can also break that flow with a special character. Scanner provides API for advanced usage like splitting using a custom function etc, scanning different types of I/O streams(Stdin, String) etc.

    0 讨论(0)
  • 2020-11-28 01:31

    You need to provide a pointer to the var you want to scan, like so:

    fmt.scan(&text2)
    
    0 讨论(0)
提交回复
热议问题