How to read from console in Go / Golang and cast to int?

This might be a simple snippet but it’s useful for those who are learning Go / GoLang.

package main

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

func main() {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter text: ")
	text, _ := reader.ReadString('\n')
	fmt.Println("The text is: " + text)
	//Replace with \r\n if on Windows and \n if on Linux
	text = strings.Replace(text, "\r\n", "", -1)
	castedText, _ := strconv.Atoi(text)
	fmt.Println(castedText)
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s