read input with golang code example
Example 1: user input golang
import (
"fmt"
"bufio"
)
//reading an integer
var age int
fmt.Println("What is your age?") // Question to the user
_, err: fmt.Scan(&age)
//reading a string
reader := bufio.newReader(os.Stdin)
var name string
fmt.Println("What is your name?") // Question to the user
name, _ := reader.readString('\n')
fmt.Println("Your name is ", name, " and you are age ", age)
}
Example 2: How to read an input in golang
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
names := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter name: ")
scanner.Scan()
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
names = append(names, text)
} else {
break
}
}
fmt.Println(names)
}