Example 1: Reading a Single Input
In this example, we declare a variable to store the user’s name. The program prompts the user for input and then greets them.Example 2: Reading Multiple Inputs
You can capture multiple inputs in a single Scanf call by using multiple format specifiers and corresponding variables. In this example, the program asks for a user’s name and then whether they are a muggle.Example 3: Handling Input Errors
The fmt.Scanf function returns two values: the number of arguments successfully read and an error if one occurred. This is useful when you need to handle input errors. Consider the following example:b remains its default zero value due to the incorrect input type.
:::
Summary
This article demonstrated how to handle user input in Go using the fmt.Scanf function. We covered:| Use Case | Description | Example Command |
|---|---|---|
| Single Input | Reading a simple string input for a variable | fmt.Scanf("%s", &name) |
| Multiple Inputs | Capturing several inputs with multiple format specifiers | fmt.Scanf("%s %t", &name, &isMuggle) |
| Error Handling | Detecting and responding to input errors using Scanf’s return value | Checking count and error values after Scanf execution |