0

This is going to be a simple question to answer, I am sure of it. I am brand new to Go and I can't figure out what is happening.

package main

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

func main() {
    fmt.Print("*A basic GoLang/Native example*\n\n")
    fmt.Print("Enter your name:\n")

    reader := bufio.NewReader(os.Stdin)
    name, _ := reader.ReadString('\n')
    name = strings.TrimSuffix(name, "\n")

    fmt.Printf("Hello, %s, how are you?", name)

    reader.ReadString('\n')

}

I am removing the newline which is stored in variable name from reading in the user input, but the last Printf statement is truncating Hello, from the line.

1 Answer 1

2

I think you are looking for strings.TrimSpace.

To remove the leading and trailing white spaces use this.

Change this line from

name = strings.TrimSuffix(name, "\n")

to

name = strings.TrimSpace(name)

Output:

*A basic GoLang/Native example*

Enter your name:
Source Cast
Hello, Source Cast, how are you?

It is working fine for both Windows and Linux.

Sign up to request clarification or add additional context in comments.

2 Comments

geez thanks, there is a book that states to remove newlines entered from user input, to use strings.TrimSuffix. I suppose that is not correct... Here is a link if you are curious. flaviocopes.com/golang-remove-new-line-from-readstring
Unfortunately it is correct for Linux but not for windows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.