Golang fmt Scanf Function

The fmt.Scanf function in Golang is part of the fmt package and is used to read formatted input from the standard input (usually the console). It reads input according to a specified format string, allowing you to parse and assign values to variables in a structured way.

Table of Contents

  1. Introduction
  2. Scanf Function Syntax
  3. Examples
    • Basic Usage
    • Reading Multiple Values with Format Specifiers
  4. Real-World Use Case
  5. Conclusion

Introduction

The fmt.Scanf function allows you to capture and parse user input using format specifiers. This provides more control over how the input is processed compared to fmt.Scan, which reads space-separated values. fmt.Scanf is useful when you need to enforce specific input formats or handle structured data.

Scanf Function Syntax

The syntax for the fmt.Scanf function is as follows:

func Scanf(format string, a ...interface{}) (n int, err error)

Parameters:

  • format: A format string containing format specifiers that define how to parse the input.
  • a: Pointers to variables where the scanned data will be stored. Each variable should match the expected input type defined by the format specifiers.

Returns:

  • n: The number of items successfully scanned and assigned.
  • err: An error if one occurred during scanning.

Common Format Specifiers:

  • %s: String
  • %d: Integer (base 10)
  • %f: Floating-point number
  • %t: Boolean
  • %v: Default format for the type

Examples

Basic Usage

This example demonstrates how to use the fmt.Scanf function to read formatted input from the user.

Example

package main

import (
	"fmt"
)

func main() {
	var name string
	var age int

	// Prompt the user for input
	fmt.Print("Enter your name and age (format: Name Age): ")

	// Use fmt.Scanf to read the input according to the format
	fmt.Scanf("%s %d", &name, &age)

	// Print the captured input
	fmt.Printf("Name: %s, Age: %d\n", name, age)
}

Console Input/Output:

Enter your name and age (format: Name Age): Alice 30
Name: Alice, Age: 30

Reading Multiple Values with Format Specifiers

You can use fmt.Scanf to enforce specific input formats, such as reading data with fixed-width fields or specific separators.

Example

package main

import (
	"fmt"
)

func main() {
	var day, month, year int

	// Prompt the user for input
	fmt.Print("Enter the date (format: DD/MM/YYYY): ")

	// Use fmt.Scanf to read the date using a specific format
	fmt.Scanf("%d/%d/%d", &day, &month, &year)

	// Print the captured date
	fmt.Printf("Day: %02d, Month: %02d, Year: %d\n", day, month, year)
}

Console Input/Output:

Enter the date (format: DD/MM/YYYY): 15/08/2024
Day: 15, Month: 08, Year: 2024

Real-World Use Case

Parsing Structured Input

In real-world applications, fmt.Scanf can be used to parse structured input, such as configuration settings or commands, from the user.

Example

package main

import (
	"fmt"
)

func main() {
	var command string
	var value int

	// Prompt the user for a command
	fmt.Print("Enter a command (format: command value): ")

	// Use fmt.Scanf to read and parse the command
	fmt.Scanf("%s %d", &command, &value)

	// Handle the command
	switch command {
	case "add":
		fmt.Printf("Adding %d to the total.\n", value)
	case "subtract":
		fmt.Printf("Subtracting %d from the total.\n", value)
	default:
		fmt.Println("Unknown command.")
	}
}

Console Input/Output:

Enter a command (format: command value): add 10
Adding 10 to the total.

Conclusion

The fmt.Scanf function is a powerful way to read and parse formatted input from the console in Go. By using format specifiers, you can control how data is captured and assigned to variables, making it ideal for applications that require structured input handling. Whether you're processing commands, parsing dates, or handling configuration settings, fmt.Scanf provides the flexibility needed to interpret input in your Go programs.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare