I\'m trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, s
8 years later I stumbled upon this gem, and yet I don't believe OP's original question was really answered:
so I came up with the following code to trim the newline character
While the bufio.Reader
type supports a ReadLine() method which both removes \r\n
and \n
it is meant as a low-level function which is awkward to use because repeated checks are necessary.
IMO an idiomatic way to remove whitespace is to use Golang's strings library:
input, _ = src.ReadString('\n')
// more specific to the problem of trailing newlines
actual = strings.TrimRight(input, "\r\n")
// or if you don't mind to trim leading and trailing whitespaces
actual := strings.TrimSpace(input)
See this example in action in the Golang playground: https://play.golang.org/p/HrOWH0kl3Ww