Go Program to Get Input from User

Go Program to Get Input from User

Scanf function from fmt library provides the feature to get input from user via keyboard.

fmt.Scanf(ā€œ%dā€, &a)

Go Example to Get Input from User

Go code is used to get user input a, b and calculates addition of a and b.

package main                                                               	 
                                                                           	 
import "fmt"                                                               	 
                                                                           	 
func main() {                                                              	 
                                                                           	 
	// declare variables                                                   	 
	var a, b int                                                           	 
                                                                           	 
	fmt.Print("Enter a and b: ")                                           	 
	// Get inputs a and b from user via keyboard                           	 
	fmt.Scanf("%d", &a)                                                    	 
	fmt.Scanf("%d", &b)                                                    	 
                                                                           	 
	// addition expression                                                 	 
	c := a + b                                                             	 
                                                                           	 
	// prints result                                                       	 
	fmt.Printf("%d + %d: %d\n", a, b, c)                                   	 
}  
Output:
$ go build user-input.go
$ ./user-input
Enter a and b: 2 4
2 + 4: 6