🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
- Introduction
ScanfFunction Syntax- Examples
- Basic Usage
- Reading Multiple Values with Format Specifiers
- Real-World Use Case
- 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment