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

How do I check if the user has entered a null value and where do I put the code? Note - I've already tried checking the length = 0 and = " " but, they don't seem to be working.

Please suggest an alternative way for doing this. Thanks!

icza
  • 389,944
  • 63
  • 907
  • 827
Rahul Prabhu
  • 69
  • 1
  • 9
  • 2
    I don't think "enter a null value" makes sense. Null is the absence of input. The closest you can get in a stream input would be a 0-length string, but as you know `""` is not the same as `nil` in Go (or almost any language). – Jonathan Hall Apr 19 '17 at 13:06
  • http://stackoverflow.com/questions/18594330/what-is-the-best-way-to-test-for-an-empty-string-in-go – Alex Kroll Apr 19 '17 at 13:11

2 Answers2

6

bufio.Reader.ReadString() returns a string that also contains the delimeter, in this case the newline character \n.

If the user does not enter anything just presses the Enter key, the return value of ReadString() will be "\n", so you have to compare the result to "\n" to check for empty input:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
text, err := reader.ReadString('\n')
if err != nil {
    panic(err) // Don't forget to check and handle returned errors!
}

if text == "\n" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}

An even better alternative would be to use strings.TrimSpace() which removes leading and trailing white space characters (newline included; it isn't a meaningful name if someone inputs 2 spaces and presses Enter, this solution also filters that out). You can compare to the empty string "" if you called strings.TrimSpace() prior:

text = strings.TrimSpace(text)
if text == "" {
    fmt.Println("No input!")
} else {
    fmt.Println("Hello", text)
}
icza
  • 389,944
  • 63
  • 907
  • 827
0

// The best algorithm I have written so far

package main

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

func main() {
    Wellcome()
    sina := get_Informations()
    fmt.Printf("%v", sina)
    Goodbye()
}

func Wellcome() {
    fmt.Println("Welcome to this Program ...[*]")
}

func get_Informations() (string){
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter First-Name: ")
    firstName, _ := reader.ReadString('\n') 
    if len(firstName) >= 5 {
        return firstName
    }
    for {
        fmt.Print("First-Name must be more than 3 characters: ")    
        firstName, _ := reader.ReadString('\n') 
        if len(firstName) < 5 {
            continue
        }else if len(firstName) >=5{
            return firstName
        } 

    }
}

func Goodbye() {
    fmt.Println("   ")
    fmt.Println("   ")
    fmt.Println(" [*]----------------------[*]  ")
    fmt.Println(" [*]----THANKS.GOODBYE----[*]  ")
    fmt.Println(" [*]----------------------[*]  ")
    fmt.Println("   ")
    fmt.Println("   ")
}