How to read from standard input in the console?

后端 未结 11 1123
迷失自我
迷失自我 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:35

    Can also be done like this:-

    package main
    import "fmt"     
    
    func main(){
        var myname string
    fmt.Scanf("%s", &myname)           
    fmt.Println("Hello", myname)       
    }
    
    0 讨论(0)
  • 2020-11-28 01:38

    Another way to read multiple inputs within a loop which can handle an input with spaces:

    package main
    import (
        "fmt"
        "bufio"
        "os"
    )
    
    func main() {
        scanner := bufio.NewScanner(os.Stdin)
        var text string
        for text != "q" {  // break the loop if text == "q"
            fmt.Print("Enter your text: ")
            scanner.Scan()
            text = scanner.Text()
            if text != "q" {
                fmt.Println("Your text was: ", text)
            }
        }
    }
    

    Output:

    Enter your text: Hello world!
    Your text was:  Hello world!
    Enter your text: Go is awesome!
    Your text was:  Go is awesome!
    Enter your text: q
    
    0 讨论(0)
  • 2020-11-28 01:38

    Try this code:-

    var input string
    func main() {
          fmt.Print("Enter Your Name=")
          fmt.Scanf("%s",&input)
          fmt.Println("Hello "+input)
          }
    
    0 讨论(0)
  • 2020-11-28 01:44

    In my case, program was not waiting because I was using watcher command to auto run the program. Manually running the program go run main.go resulted in "Enter text" and eventually printing to console.

    fmt.Print("Enter text: ")
    var input string
    fmt.Scanln(&input)
    fmt.Print(input)
    
    0 讨论(0)
  • 2020-11-28 01:47

    I'm not sure what's wrong with the block

    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter text: ")
    text, _ := reader.ReadString('\n')
    fmt.Println(text)
    

    As it works on my machine. However, for the next block you need a pointer to the variables you're assigning the input to. Try replacing fmt.Scanln(text2) with fmt.Scanln(&text2). Don't use Sscanln, because it parses a string already in memory instead of from stdin. If you want to do something like what you were trying to do, replace it with fmt.Scanf("%s", &ln)

    If this still doesn't work, your culprit might be some weird system settings or a buggy IDE.

    0 讨论(0)
提交回复
热议问题