reading input in 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: golang get terminal input

package main

import (
  "bufio"
  "fmt"
  "os"
  "strings"
)

func main() {

  reader := bufio.NewReader(os.Stdin)
  fmt.Println("Simple Shell")
  fmt.Println("---------------------")

  for {
    fmt.Print("-> ")
    text, _ := reader.ReadString('\n')
    // convert CRLF to LF
    text = strings.Replace(text, "\n", "", -1)

    if strings.Compare("hi", text) == 0 {
      fmt.Println("hello, Yourself")
    }

  }

}

Example 3: 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)
}

Tags:

Go Example