🔥 NEW! Get my book The Developer's Guide to Having a Successful Blog

In this book I teach you all I know about starting and growing a blog.
Launch promo: 25% OFF until tomorrow! And a special challenge for you!


Suppose you I want to get a number from stdin, using io.Reader.ReadString, and you want to convert this number to an integer.

Before being able to convert it to integer using strconv.Atoi, you have to remove the new line char.

How can you do so?

Solution

Using strings.TrimSuffix:

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	text, _ := reader.ReadString('\n')
	text = strings.TrimSuffix(text, "\n")
}