Golang Program - Print value by reading user input from console


In this blog post, input data can be read from the console in the may ways in Go language

  • read input values using the scan function
  • read multiple input values from console
  • read user input line by line using stdin stream

Example to read user input using the scan function

package main  
import (  
 "fmt"  
)  
  
func main() {  
 //reading an string  
 var name string  
 fmt.Print("What is your Name? ")  
 fmt.Scan(&name)  
 fmt.Println("Entered Name is :", name)  
  
}  

Output is

What is your Name? kiran babu  
Entered Name is : kiran  

In the above example, a String variable is declared.

package fmt has a Scan function, fmt package is imported into the program

Function Scan is used to read the user input from the standard input ie console. input values are stored with separation of space into successive parameters.

You can check more about scan function. Scan function store the address or pointer of the variable.

What is your Name? prompt is displayed to the user to take input from user

fmt.Scan(&name) function read all values separated in spaces until newline(\n or enter keyword). Each word separated in spaces are stored in variable name.

As we declared only one variable - name, text “kiran babu” will be treat as two variable in space separated format, the first value is stored in the variable name

Finally, printing entered a value into the console

The only disadvantages with this is entered text is saved in multiple variables, not complete line.

Here is an example for reading multiple input values

package main  
import (  
 "fmt"  
)  
  
func main() {  
 //reading an multiple input string  
 var fname string  
 var lname string  
 fmt.Print("What is your Name? ")  
 fmt.Scanln(&fname, &lname)  
 fmt.Printf("Entered Name is %s %s", fname, lname)  
}  

Output is

What is your Name? Cloud Hadoop  
Entered Name is Cloud Hadoop  

Next example is to read user input line by line using the stdin stream

Example program to read user input line using stdin stream

Bufio package provides to read/write from any stream.
bufio package has Scanner class to read line by line from input console
bufio.NewScanner which accepts io.Reader to scan line by line from a given stream.

bufio.NewScanner(os.Stdin) read data from keyword line by line  from command line console
Finally scanner.text() stores the user text and print it to console
Following is read input line by line from command line console using stdin stream

package main  
import (  
 "bufio"  
 "fmt"  
 "log"  
 "os"  
)  
  
func main() {  
 fmt.Println("Pleae enter text")  
 scanner := bufio.NewScanner(os.Stdin)  
 for scanner.Scan() {  
  fmt.Println("Entered Text is ", scanner.Text())  
 }  
 // Error handling  
 if err := scanner.Err(); err != nil {  
  log.Println(err)  
 }  
  
}  

Output is

What is your Name? Kiran  
Entered Name is Kiran  

Similar Posts