Lesson 5 · 5 of 20
Reading input · Go
Read lines from the keyboard in Go with bufio.Scanner and turn them into numbers with strconv.Atoi and strconv.ParseFloat to do maths.

bufio.NewScanner(os.Stdin) creates a Scanner that reads standard input, that is, whatever is typed. Each scanner.Scan() waits for a line and scanner.Text() returns it, already without the final newline.
In this example the answers come from the input.txt file, as if someone were typing them, which is why they do not appear in the output: you see the question, printed with fmt.Print so that the answer stays on the same line, followed by the program's reply. In the DMarlon Studio console you can type them yourself.
Text() always gives a string, even if you type 29. To do maths you have to convert it: strconv.Atoi turns it into an int and returns two values, the number and an error. If the text is not a number, err is not nil, so the program says so and stops with return. Errors get their own lesson, number 13.
strconv.ParseFloat(text, 64) converts to a float64. Here the error is thrown away with _, the blank identifier, because the example assumes the price is valid: three tickets at 8.50 cost 25.50 euros.
Code · main.go
package mainimport ( "bufio" "fmt" "os" "strconv")func main() { // A Scanner reads the keyboard (standard input) line by line. scanner := bufio.NewScanner(os.Stdin) fmt.Print("What is your name? ") scanner.Scan() name := scanner.Text() fmt.Printf("Nice to meet you, %s!\n", name) // Text() is always a string: convert it to do maths. fmt.Print("How old are you? ") scanner.Scan() age, err := strconv.Atoi(scanner.Text()) if err != nil { fmt.Println("That is not a whole number.") return } fmt.Printf("In 10 years you will be %d.\n", age+10) fmt.Print("Price of a cinema ticket? ") scanner.Scan() price, _ := strconv.ParseFloat(scanner.Text(), 64) fmt.Printf("Three tickets cost %.2f euros.\n", price*3)}Input (what gets typed) · input.txt
Lucia 29 8.50
Output · go run main.go
What is your name? Nice to meet you, Lucia! How old are you? In 10 years you will be 39. Price of a cinema ticket? Three tickets cost 25.50 euros.
Key points
bufio.NewScanner(os.Stdin)reads the keyboard.scanner.Scan()reads a line andscanner.Text()gives it.- Input is text:
strconv.Atoiandstrconv.ParseFloatconvert it. - Conversions also return an error;
nilmeans it went well. _throws away a value you will not use.
Exercise
Also ask how many tickets to buy, convert the answer with strconv.Atoi checking the error, and print the total price with two decimals.