gogofmt

Terminal input doesn't match expected result


I am new to Go.

I wrote the program below to allow a user to enter the name.

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)

    fmt.Print("Enter name:")
    name, err := reader.ReadString('\n')
    if err != nil {
        panic(err)
    }

    fmt.Println(name == "nixon")
}

I ran the program and entered my name nixon

Why is it that the output of fmt.Println(name == "nixon") is always false?


Solution

  • func (*Reader) ReadString

    func (b *Reader) ReadString(delim byte) (string, error)
    

    ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.


    name terminal input includes trailing newlines. For example,

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
    )
    
    func main() {
        reader := bufio.NewReader(os.Stdin)
    
        fmt.Print("Enter name:")
        name, err := reader.ReadString('\n')
        if err != nil {
            panic(err)
        }
        fmt.Printf("%q\n", name)
    
        fmt.Println(name == "nixon")
    }
    

    Output (Linux):

    Enter name:nixon
    "nixon\n"
    false
    

    Output (Windows):

    Enter name:nixon
    "nixon\r\n"
    false
    

    Trim trailing newlines. For example,

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
        "strings"
    )
    
    func main() {
        reader := bufio.NewReader(os.Stdin)
    
        fmt.Print("Enter name:")
        name, err := reader.ReadString('\n')
        if err != nil {
            panic(err)
        }
        fmt.Printf("%q\n", name)
        name = strings.TrimRight(name, "\r\n")
        fmt.Printf("%q\n", name)
    
        fmt.Println(name == "nixon")
    

    }

    Output (Linux):

    Enter name:nixon
    "nixon\n"
    "nixon"
    true
    

    Output (Windows):

    Enter name:nixon
    "nixon\r\n"
    "nixon"
    true