Go - Read Input From User With Scanf

1. Introduction

Interactivity is a crucial aspect of many Go programs, and reading user input is a common requirement. Go provides a straightforward way to accomplish this using the Scanf function from the fmt package. This post will guide you through reading user input from the console using Scanf in Go.

2. Program Steps

1. Import the fmt package to use the Scanf function.

2. Prompt the user to enter their input.

3. Use the Scanf function to read and parse the user input.

4. Store the values in the appropriate variables.

5. Output the values to verify that the input was read correctly.

3. Code Program

package main

import "fmt"

func main() {
	// Variables to store user input
	var name string
	var age int

	// Step 2: Prompt the user for their name and age
	fmt.Println("Please enter your name and age:")

	// Step 3: Use Scanf to read the input
	// %s reads a string until the first space, %d reads a decimal number
	fmt.Scanf("%s %d", &name, &age)

	// Step 5: Output the values to verify the input
	fmt.Printf("Name: %s, Age: %d\n", name, age)
}

Output:

Please enter your name and age:
John 25
Name: John, Age: 25

Explanation:

1. The program starts with package main, defining the main package for an executable Go program.

2. import "fmt" is included to use I/O functions.

3. Two variables, name of type string and age of type int, are declared to store user input.

4. The program prompts the user for their name and age using fmt.Println.

5. fmt.Scanf reads formatted input from the console. It uses %s to read a string (until a space) and %d to read an integer. The '&' prefix is used to pass the memory address of name and age so Scanf can store the inputted values directly in these variables.

6. The program prints the inputted name and age to the console with fmt.Printf to verify that it has read the input correctly.

7. The output shows that if a user types 'John 25', the program correctly reads the input and prints "Name: John, Age: 25".


Comments