0
0
GoHow-ToBeginner · 3 min read

How to Use fmt.Scanf in Go: Simple Input Reading

Use fmt.Scanf in Go to read formatted input from standard input by specifying a format string and pointers to variables. It reads input matching the format and stores values in the provided variables.
📐

Syntax

The basic syntax of fmt.Scanf is:

  • fmt.Scanf(format string, &variable1, &variable2, ...)

Here, format string defines how input should be read (like %d for integers, %s for strings).

The variables are passed by reference using & so that Scanf can store the input values in them.

go
fmt.Scanf(format string, &var1, &var2, ...)
💻

Example

This example shows how to read a name and age from the user using fmt.Scanf:

go
package main

import (
	"fmt"
)

func main() {
	var name string
	var age int

	fmt.Print("Enter your name and age: ")
	n, err := fmt.Scanf("%s %d", &name, &age)
	if err != nil {
		fmt.Println("Error reading input:", err)
		return
	}
	fmt.Printf("Read %d items. Name: %s, Age: %d\n", n, name, age)
}
Output
Enter your name and age: Alice 30 Read 2 items. Name: Alice, Age: 30
⚠️

Common Pitfalls

Common mistakes when using fmt.Scanf include:

  • Not using & before variables, so input cannot be stored.
  • Incorrect format strings that don't match input, causing errors or partial reads.
  • Input buffering issues, where leftover input causes unexpected behavior.
  • Not checking the number of items successfully scanned or errors returned.

Always check the returned values and errors to handle input properly.

go
package main

import (
	"fmt"
)

func main() {
	var age int

	// Wrong: missing & before age
	// fmt.Scanf("%d", age) // This will cause a compile error

	// Right way:
	fmt.Print("Enter your age: ")
	n, err := fmt.Scanf("%d", &age)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Printf("Read %d item(s). Age: %d\n", n, age)
}
Output
Enter your age: 25 Read 1 item(s). Age: 25
📊

Quick Reference

Tips for using fmt.Scanf effectively:

  • Use format verbs like %d (int), %f (float), %s (string).
  • Always pass variables by reference with &.
  • Check the number of items scanned and error returned.
  • Input must match the format exactly, including spaces.
  • Use fmt.Scanln or bufio.Scanner for more flexible input reading.

Key Takeaways

Use fmt.Scanf with a format string and pointers to variables to read formatted input.
Always pass variables by reference using & so values can be stored.
Check the number of items scanned and handle errors to avoid unexpected input issues.
Input must match the format string exactly, including spaces and types.
For more flexible input, consider fmt.Scanln or bufio.Scanner instead of Scanf.