0
package main

import (
    "bufio"
    "fmt"
    "os"
)

func Option1() {
     fmt.Println("Option1")
}
func main() {
     for true {
         fmt.Println("Pleae enter text: ")
         reader := bufio.NewReader(os.Stdin)
         text, _ := reader.ReadString('\n')
         if text == "1" {
                Option1()
         }

      }
 }

So my code will eventually have multi functions example: option1 option2 and etc.. I'm trying to execute a function every time a user types 1, 2, 3 and etc, but my code doesn't print out whatever is in Option1.

Your help will be appreciated.

9
  • 2
    From the docs: "ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter." (emphasis mine). Commented May 4, 2020 at 20:29
  • 3
    The delimiter \n is included in the value returned by ReadString. In addition, the program discards data buffered from stdin. Use a Scanner instead. See this question for more info. Commented May 4, 2020 at 20:29
  • You can also just check the value of text[:1]. Commented May 4, 2020 at 20:33
  • @larsks That will not work as you expect on all operating systems. Use a Scanner. Commented May 4, 2020 at 20:35
  • 2
    for { fmt.Println(prompt); if !scanner.Scan() { break }; text := scanner.Text(); /* do something with text */} Commented May 4, 2020 at 21:17

1 Answer 1

1

Ground rule is ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. So I used text = strings.TrimSpace(text) to trim it before comparing .See the modified program.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func Option1() {
    fmt.Println("Option1")
}
func main() {

    for true {
        fmt.Println("Pleae enter text: ")
        reader := bufio.NewReader(os.Stdin)
        text, _ := reader.ReadString('\n')
        fmt.Println("Length of text,before trimming:", len(text))
        text = strings.TrimSpace(text)
        fmt.Println("Length of text,after trimming:", len(text))
        if text == "1" {
            Option1()
        }

    }
}

Oputput is

VScode> go run sofstringcompare.go
Pleae enter text: 
1
Length of text,before trimming: 3
Length of text,after trimming: 1
Option1
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.