I'm a new in golang and i don't understand why I can't get next code working:
func ListApps(){
fmt.Printf("
Press Q to go back..
")
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('
')
if string(input) == "q" {
fmt.Printf("OK")
}
}
I want to print a message, then scan user's input in console, compare input and print messafe if imput equals string "q". Last check doesn't work for some reasons.
from TFM:
ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter
You are comparing the string without the delimiter.
So just doing:
if input == "q
" {...}
would work (BTW no need to call string(input)
as input is already a string).
Alternatively you can also trim the endline before checking, using strings.TrimRight
. This will make the code more portable as it will work on Windows where is used to delimit lines. So do this:
input = strings.TrimRight(input, "
")
if input == "q" {
fmt.Println("OK")
}
And I've tested this to work myself.
Not_a_Golfer is correct on why its not working. However, for simple things like reading from STDIN you're better off using Scanner:
func ListApps(){
fmt.Printf("
Press Q to go back..
")
reader := bufio.NewScanner(os.Stdin)
reader.Scan() // this line scans the STDIN for input
// error checking...
if err := scanner.Err(); err != nil {
panic(err)
}
// To access what the scanner got, you use scanner.Text() (reader.Text() in this case)
if reader.Text() == "q" {
fmt.Printf("OK")
}
}
This will work, regardless of where the input is from (windows command prompt, terminal on linux/OSX, etc)