I am playing around with Go. I want to make it so when someone enters 'hi' it prints hiii
Here is my code
package main
import (
"fmt"
"bufio"
"os"
)
func main(){
reader := bufio.NewReader(os.Stdin)
fmt.Println("Simple Shell")
fmt.Println("---------------------")
for {
fmt.Print("-> ")
text, _ := reader.ReadString('
')
if (text == "hi") {
fmt.Println("hiii")
}
}
}
Just add such that
if text == "hi
" {
fmt.Println("hiii")
}
There is a trick to that: When using ReadString and ReadBytes function with a delimiter, the returned string (and bytes) contains the delimiter. That's why the condition is not true, your actual string is "hi " and not "hi".
In order to read from stdin, you can use the ReadLine function, or manually trim the end line characters with packages strings
and bytes
.
Also, you can use a Scanner, it reads lines by default. Here are some examples which all do the same job:
package main
import (
"bufio"
"bytes"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("-> ")
text, _, _ := reader.ReadLine()
if string(text) == "hi" {
fmt.Println("hii")
}
fmt.Print("-> ")
stext, _ := reader.ReadString('
') // stext ends with '
', it reads the delimiter
stext = strings.TrimRight(stext, "
")
if stext == "hi" {
fmt.Println("hii")
}
fmt.Print("-> ")
text, _ = reader.ReadBytes('
')
text = bytes.TrimRight(text, "
")
if string(text) == "hi" {
fmt.Println("hii")
}
fmt.Print("-> ")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
stext = scanner.Text()
if stext == "hi" {
fmt.Println("hii")
}
fmt.Print("−> ")
scanner.Scan()
text = scanner.Bytes()
if string(text) == "hi" {
fmt.Println("hii")
}
}