Back to Blog

User Input (fmt.Scan, bufio, os.Args, strconv) - Go Tutorial for Beginners #5

Sandy LaneSandy Lane

Video: User Input (fmt.Scan, bufio, os.Args, strconv) - Go Tutorial for Beginners #5 by Taught by Celeste AI - AI Coding Coach

Watch full page →

User Input in Go: fmt.Scan, bufio, os.Args, and strconv

Reading user input is essential for interactive Go programs. This guide covers basic input methods using fmt.Scan and fmt.Scanln, reading entire lines with bufio.Reader and bufio.Scanner, accessing command-line arguments via os.Args, and converting string input to numbers or booleans using the strconv package.

Code

package main

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

func main() {
  // 1. Basic input with fmt.Scan and fmt.Scanln
  var name string
  var age int
  fmt.Print("Enter your name and age: ")
  fmt.Scan(&name, &age) // reads space-separated inputs
  fmt.Printf("Hello %s, you are %d years old.\n", name, age)

  // 2. Reading a full line with bufio.Reader
  reader := bufio.NewReader(os.Stdin)
  fmt.Print("Enter a full sentence: ")
  sentence, _ := reader.ReadString('\n') // reads until newline
  sentence = strings.TrimSpace(sentence)
  fmt.Println("You typed:", sentence)

  // 3. Reading input line by line with bufio.Scanner
  scanner := bufio.NewScanner(os.Stdin)
  fmt.Println("Enter lines (type 'stop' to end):")
  for scanner.Scan() {
    line := scanner.Text()
    if line == "stop" {
      break
    }
    fmt.Println("Line:", line)
  }

  // 4. Accessing command-line arguments with os.Args
  fmt.Println("Command-line arguments:")
  for i, arg := range os.Args {
    fmt.Printf("Arg %d: %s\n", i, arg)
  }

  // 5. Parsing strings to numbers and booleans
  strNum := "42"
  num, err := strconv.Atoi(strNum) // convert string to int
  if err == nil {
    fmt.Println("Parsed integer:", num)
  }

  strFloat := "3.14"
  f, err := strconv.ParseFloat(strFloat, 64) // convert string to float64
  if err == nil {
    fmt.Println("Parsed float:", f)
  }

  strBool := "true"
  b, err := strconv.ParseBool(strBool) // convert string to bool
  if err == nil {
    fmt.Println("Parsed bool:", b)
  }
}

Key Points

  • fmt.Scan and fmt.Scanln read space-separated input values directly into variables.
  • bufio.Reader and bufio.Scanner allow reading full lines or multiple lines from standard input.
  • os.Args provides access to command-line arguments passed to the program.
  • The strconv package converts strings to numeric and boolean types with functions like Atoi, ParseFloat, and ParseBool.
  • Always handle errors when parsing strings to avoid runtime issues with invalid input.