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)
}

Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *