I would like to read 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 equivalent of Console.ReadLine() in C#.
This is what I currently have:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, _ := reader.ReadString('\n')
fmt.Println(text)
fmt.Println("Enter text: ")
text2 := ""
fmt.Scanln(text2)
fmt.Println(text2)
ln := ""
fmt.Sscanln("%v", ln)
fmt.Println(ln)
}
I'm not sure what's wrong with the block
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)
withfmt.Scanln(&text2)
. Don't useSscanln
, 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 withfmt.Scanf("%s", &ln)
If this still doesn't work, your culprit might be some weird system settings or a buggy IDE.
I think a more standard way to do this would be:
Take a look at the
scan
godoc: http://godoc.org/fmt#ScanCleanly read in a couple prompted values:
Here's a run:
Another way to read multiple inputs within a loop which can handle an input with spaces:
Output:
Try this code:-
You need to provide a pointer to the var you want to scan, like so: