Level: BeginnerGo Programs

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

Updated 17 min read
Go User Input featured image: prompt reading a name and command line numbers

Go user input programs let your code ask a question and use the answer, which is the moment a program starts to feel alive. In this post, you will read words, numbers and full lines from the keyboard, and you will also read values from the command line. Every program comes with sample input and its exact output, followed by the input questions interviewers ask most.

Before you start, finish our Go print programs with output, because every input program also prints. You should also know how to run a Go program from a terminal. We tested every program on Go 1.27.

What is Go User Input?

User input is any data your program receives while it runs. It can come from the keyboard, from command line arguments or from another program through a pipe. In Go, the keyboard input arrives on standard input, which the os package calls os.Stdin.

Think of standard input as a letterbox. The user drops text into it, and your program picks the text up when it is ready. Different tools pick it up in different ways, one word at a time or one full line at a time.

Why Go User Input Matters

Almost every useful tool needs Go user input of some kind. For example, a calculator needs numbers, a quiz needs answers and a login screen needs a name. Coding rounds also give their test data on standard input, so you must read it quickly and correctly.

  • Coding tests: sites like HackerRank and LeetCode style judges send input on stdin.
  • Command line tools: tools read flags such as -port=8080 when they start.
  • Scripts: one program can pipe its output into another Go program.

How Go User Input Works

Your program can read Go user input in three main ways. The diagram shows where each one gets its data.

Go user input diagram showing keyboard, command line arguments and pipes flowing into a Go program
Keyboard text and pipes arrive on os.Stdin, while command line arguments arrive in os.Args before the program starts.

The table below shows which tool to pick for each job.

ToolReadsBest for
fmt.ScanWords separated by spaces or new linesQuick numbers and single words
fmt.ScanlnWords on one line onlyOne line of values
fmt.ScanfValues in a fixed formatInput like 10-20
bufio.ReaderOne full line with spacesNames and sentences
bufio.ScannerMany lines in a loopFiles and big test input
os.ArgsWords after the program nameSimple command line tools
flagNamed options like -nameReal command line tools

In each example below, we first show the input you type. Then we show the output. In a real terminal, you will also see your typed text after each prompt.

Go User Input with fmt.Scan

fmt.Scan is the simplest way to read Go user input. It reads words separated by spaces or new lines and stores them in the variables you pass. You must pass a pointer, written with &, so Scan can change your variable.

Program 1: Read Your Name

This program asks for a name and greets the user.

package main

import "fmt"

// main asks for a name and says hello
func main() {
    var name string // an empty text variable to hold the answer

    fmt.Print("Enter your name: ") // Print keeps the cursor on the same line
    fmt.Scan(&name)                // & gives Scan the address of name, so it can fill it
    fmt.Println("Hello,", name+"!") // + joins the name and the "!"
}
Asha
Enter your name: Hello, Asha!

&name passes the address of name, so Scan can fill it. We used Print for the prompt, so the cursor stays on the same line.

Program 2: Add Two Numbers

Scan can fill many variables in one call. It also converts the text to the right type for you.

package main

import "fmt"

// main reads two whole numbers and prints their sum
func main() {
    var first, second int // two int variables, both start at 0

    fmt.Print("Enter two numbers: ")
    fmt.Scan(&first, &second) // Scan fills them in order and turns the text into ints

    fmt.Println("Sum:", first+second)
}
12 30
Enter two numbers: Sum: 42

The user can type both numbers on one line or on two lines. Scan treats spaces and new lines the same way.

Program 3: Answer a Yes or No Question

Go user input becomes useful when your program makes a choice with it. This program reads one word and answers in two different ways.

package main

import "fmt"

// main asks a question and replies based on the answer
func main() {
    var answer string

    fmt.Print("Do you like Go? (yes/no): ")
    fmt.Scan(&answer)

    // == checks if two strings are exactly the same
    if answer == "yes" {
        fmt.Println("Great! Let's write more Go.")
    } else {
        fmt.Println("Give it a week. It grows on you.")
    }
}
yes
Do you like Go? (yes/no): Great! Let's write more Go.

First, Scan stores the typed word in answer. Then the if compares it with “yes”. If they match, the first message prints, and any other word prints the second one.

Program 4: Check for Bad Input

What if the user types letters instead of a number? Scan returns an error, and you should always check it.

package main

import "fmt"

// main reads an age and stops kindly if the input is not a number
func main() {
    var age int
    fmt.Print("Enter your age: ")

    // Scan returns two values: how many items it read, and err (the error value)
    // _ means we do not need the first value
    _, err := fmt.Scan(&age)

    // nil means "no error", so != nil means something went wrong
    if err != nil {
        fmt.Println("Invalid input:", err)
        return // stop main here
    }
    fmt.Println("Next year you will be", age+1)
}
abc
Enter your age: Invalid input: expected integer

Scan returns two values: how many items it read and an error. Here the error says it expected an integer, so the program stops kindly instead of using a wrong value.

Read a Full Line of Go User Input

fmt.Scan stops at the first space. So for a full name like “Asha Mehta”, you need a line reader from the bufio package.

Program 5: Read a Full Name with bufio.Reader

bufio.NewReader wraps standard input. Its ReadString method reads until it finds the character you give it, here the new line.

package main

import (
    "bufio"   // bufio reads input in bigger pieces, such as full lines
    "fmt"
    "os"      // os.Stdin is the keyboard input
    "strings" // helpers for working with text
)

// main reads a full name and counts its letters without the spaces
func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter your full name: ")

    // Step 1: read everything up to and including the new line
    line, _ := reader.ReadString('\n')

    // Step 2: remove the new line and any extra spaces at the ends
    name := strings.TrimSpace(line)

    // Step 3: drop the spaces inside the name, then count what is left
    letters := strings.ReplaceAll(name, " ", "")
    fmt.Printf("Welcome, %s! Your name has %d letters.\n", name, len(letters))
}
Asha Mehta
Enter your full name: Welcome, Asha Mehta! Your name has 9 letters.

ReadString keeps the new line at the end, so we remove it with strings.TrimSpace. This also removes the \r that Windows adds, which avoids a very common bug.

Program 6: Read Many Lines with bufio.Scanner

bufio.Scanner reads one line per loop. It stops when the input ends, which is how judges send test data.

package main

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

// main prints every input line with its line number
func main() {
    scanner := bufio.NewScanner(os.Stdin)
    count := 0

    // scanner.Scan() reads the next line and returns false when input ends
    for scanner.Scan() {
        count++
        fmt.Printf("Line %d: %s\n", count, scanner.Text()) // Text() gives the line without the new line
    }
    fmt.Println("Total lines:", count)
}
apple
banana
cherry
Line 1: apple
Line 2: banana
Line 3: cherry
Total lines: 3

scanner.Scan() returns false at the end of input, so the loop stops by itself. scanner.Text() gives the line without the new line character.

Program 7: Count the Words in a Sentence

Here is an everyday use of a full line of Go user input. The program reads a sentence and tells you how many words it has.

package main

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

// main reads one sentence and counts its words
func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Type a sentence: ")
    line, _ := reader.ReadString('\n')

    // Fields splits the text at spaces and gives back a slice (list) of words
    words := strings.Fields(line)

    fmt.Println("Words:", len(words))
    fmt.Println("First word:", words[0]) // [0] is the first item in the list
}
Go makes simple programs
Type a sentence: Words: 4
First word: Go

First, ReadString reads the whole line, spaces and all. Then strings.Fields cuts it into words wherever it finds spaces. Finally, len counts the words, and words[0] picks the first one.

Program 8: Convert Text to a Number with strconv

Line readers give you text. To do maths, convert it with strconv.Atoi, which also reports bad input.

package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv" // strconv converts between text and numbers
    "strings"
)

// main reads a price as text, turns it into a number and adds 18% GST
func main() {
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Enter price: ")
    text, _ := reader.ReadString('\n')

    // Atoi means "ASCII to integer"; it returns the number and an error
    price, err := strconv.Atoi(strings.TrimSpace(text))
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    withTax := price * 118 / 100 // 100% of the price plus 18% tax
    fmt.Println("Price with 18% GST:", withTax)
}
500
Enter price: Price with 18% GST: 590

If the user typed “five hundred”, Atoi would return the error strconv.Atoi: parsing "five hundred": invalid syntax. So the check keeps the program safe.

Formatted Go User Input with Scanf and Sscan

Sometimes Go user input has a fixed shape, such as a date or “name age”. The Scanf and Sscan family can read it in one step.

Program 9: Read a Date with Scanf

Scanf uses verbs like Printf. Any other text in the format, such as the dashes here, must match the input exactly.

package main

import "fmt"

// main reads a date typed as dd-mm-yyyy
func main() {
    var day, month, year int
    fmt.Print("Enter date (dd-mm-yyyy): ")

    // each %d reads one whole number; the dashes must appear in the input too
    fmt.Scanf("%d-%d-%d", &day, &month, &year)

    fmt.Printf("Day %d, Month %d, Year %d\n", day, month, year)
}
15-08-2026
Enter date (dd-mm-yyyy): Day 15, Month 8, Year 2026

%d read “08” as 8, because a number has no leading zeros. The dashes in the format matched the dashes in the input.

Program 10: Parse a String with Sscan

Sscan reads from a string instead of the keyboard. It is handy when you already have a line of text.

package main

import "fmt"

// main pulls a name, an age and a weight out of one string
func main() {
    record := "Ravi 30 72.5"

    var name string
    var age int
    var weight float64

    // Sscan returns how many values it read (count) and err (the error value)
    count, err := fmt.Sscan(record, &name, &age, &weight)
    fmt.Println(count, err)
    fmt.Printf("%s is %d years old and weighs %.1f kg\n", name, age, weight)
}
3 <nil>
Ravi is 30 years old and weighs 72.5 kg

count is 3 because all three values were read. This program needs no keyboard, so it also runs in the Go Playground.

Go User Input from the Command Line

Command line arguments are another kind of Go user input. They are words you type after the program name. They are ready before main starts, so the program does not wait for the user.

Program 11: Sum Numbers from os.Args

os.Args is a slice of strings. The first item is the program path, so your values start at index 1.

package main

import (
    "fmt"
    "os"
    "strconv"
)

// main adds every number typed after the program name
func main() {
    total := 0

    // os.Args[1:] skips item 0 (the program path)
    // range gives each word in turn; _ skips its position
    for _, arg := range os.Args[1:] {
        number, err := strconv.Atoi(arg)
        if err != nil {
            fmt.Println("Skipping", arg)
            continue // jump to the next word
        }
        total += number
    }
    fmt.Println("Sum:", total)
}

We run it with three numbers after the program name.

go run . 10 20 30
Sum: 60

The loop skips any word that is not a number. Our Go for loops guide explains range in detail.

Program 12: Named Options with the flag Package

The flag package reads options like -name=Asha. It also gives default values and a help message for free.

package main

import (
    "flag" // flag reads named options such as -name=Meera
    "fmt"
)

// main reads -name and -age options and prints a greeting
func main() {
    // each line gives: option name, default value, help text
    name := flag.String("name", "Guest", "your name")
    age := flag.Int("age", 18, "your age")

    flag.Parse() // read the options from the command line

    // name and age are pointers, so * gets the value they point to
    fmt.Printf("Hello %s, you are %d\n", *name, *age)
}

We pass both options when we run it.

go run . -name=Meera -age=28
Hello Meera, you are 28

flag.String returns a pointer, so we print *name. Without options, the program prints “Hello Guest, you are 18”. Our Go flag package guide covers more option types.

Go User Input: Scan vs bufio

Beginners often ask which reader to use for Go user input. The diagram and table below compare the two most common choices.

Go user input comparison of fmt.Scan and bufio readers
fmt.Scan is quick for single words and numbers, while bufio reads whole lines and large input fast.
Featurefmt.Scanbufio.Reader or Scanner
Reads spaces in textNo, stops at a spaceYes, the full line
Converts to int for youYesNo, use strconv
Speed on big inputSlowFast
Error checkingReturns an errorReturns an error
Best forSmall programsLines, files and judges

In short, use fmt.Scan for a few numbers, and bufio for full lines or large input.

Common Mistakes with Go User Input

  • Forgetting the &: fmt.Scan(name) cannot change name. Always pass &name.
  • Expecting Scan to read spaces: it stops at the first space, so “Asha Mehta” becomes “Asha”.
  • Keeping the new line: ReadString('\n') keeps it, so trim the text before you compare it.
  • Ignoring errors: a letter typed into an int gives zero, so check err every time.
  • Mixing bufio and fmt.Scan: bufio reads ahead into its buffer, so a later fmt.Scan can find nothing left to read.

Best Practices for Go User Input

  • Check every error, so bad input never turns into wrong results.
  • Trim input with strings.TrimSpace, which also fixes Windows line endings.
  • Choose one reader per program, rather than mixing fmt.Scan and bufio.
  • Prefer bufio.Scanner for big input, because it is much faster in coding tests.
  • Print a clear prompt, so the user knows what to type.

Go User Input Interview Questions and Answers

These Go user input questions come up often in interviews. We show the input and the real output for every program, tested on Go 1.27.

fmt.Scan Questions

Q1. Why do we write &name in fmt.Scan(&name)?

Scan must change your variable, so it needs its memory address. In Go, arguments are copied. Without &, Scan would only get a copy and could not fill the real variable.

Q2. What does this program print?

package main

import "fmt"

// main reads one word and prints it
func main() {
    var first string
    fmt.Scan(&first) // Scan stops at the first space
    fmt.Println("Got:", first)
}
Asha Mehta
Got: Asha

Scan stops at the first space, so only “Asha” is stored. Use bufio.Reader to read the full line.

Q3. What is the difference between Scan, Scanln and Scanf?

Scan treats new lines like spaces. Scanln stops at the end of the line, even if some variables are still empty. Scanf reads values in a pattern you give it, such as %d-%d.

Q4. What does this program print?

package main

import "fmt"

// main tries to read two numbers from one line
func main() {
    var first, second int
    count, err := fmt.Scanln(&first, &second) // count is how many values were read
    fmt.Println(count, err, first, second)
}
5
1 unexpected newline 5 0

Scanln read 5, then hit the end of the line before it found a second number. So it returns 1 and an “unexpected newline” error, and second stays 0.

Q5. What happens if you type a decimal into an int with Scan?

package main

import "fmt"

// main reads a whole number and prints it with the error value
func main() {
    var number int
    _, err := fmt.Scan(&number)
    fmt.Println(number, err)
}
3.7
3 <nil>

Scan reads the 3 and stops at the dot, because a dot cannot be part of an int. The rest, “.7”, stays in the input for the next read. Always validate input that must be a whole number.

bufio and Line Questions

Q6. Why does my string comparison fail after ReadString?

ReadString('\n') keeps the new line, and Windows also adds \r. So “yes\r\n” is not equal to “yes”. Fix it with strings.TrimSpace(line).

Q7. What does this program print?

package main

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

// main shows the bug you get when you mix bufio and fmt.Scan
func main() {
    reader := bufio.NewReader(os.Stdin)
    name, _ := reader.ReadString('\n') // reads ahead into its own buffer

    var age int
    _, err := fmt.Scan(&age) // reads os.Stdin directly, but it is already empty

    // %q shows the text in quotes, so you can see the hidden \n
    fmt.Printf("name=%q age=%d err=%v\n", name, age, err)
}
Asha
25
name="Asha\n" age=0 err=EOF

Here the input comes from a pipe, as in a coding test. bufio.Reader reads a big block into its own buffer, so it took “25” as well. When fmt.Scan then reads os.Stdin directly, nothing is left, and it returns EOF. When you type line by line in a terminal, it may seem to work, which makes this bug hard to find. So never mix bufio and fmt.Scan on the same input.

Q8. What is the line limit of bufio.Scanner?

By default, one line can be up to 64 KB (bufio.MaxScanTokenSize). For longer lines, call scanner.Buffer with a bigger buffer, or Scan stops with an error.

Q9. How do you read words instead of lines with bufio.Scanner?

Call scanner.Split(bufio.ScanWords) before the loop. Then each Scan returns one word.

package main

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

// main counts every word in the input
func main() {
    scanner := bufio.NewScanner(os.Stdin)
    scanner.Split(bufio.ScanWords) // read one word at a time instead of one line

    words := 0
    for scanner.Scan() {
        words++
    }
    fmt.Println("Words:", words)
}
Go is simple
and fast
Words: 5

The input has five words over two lines. With ScanWords, each loop reads one word, so words ends at 5.

Q10. How do you know when input has ended?

scanner.Scan() returns false, and scanner.Err() is nil if the end was normal. With fmt.Scan, the error is io.EOF. The user can send the end of input with Ctrl+D on Linux and macOS, or Ctrl+Z then Enter on Windows.

Conversion and Command Line Questions

Q11. What does this program print?

package main

import (
    "fmt"
    "strconv"
)

// main tries to convert two strings that are not clean numbers
func main() {
    first, err := strconv.Atoi("42abc") // letters after the digits
    fmt.Println(first, err)

    second, err := strconv.Atoi(" 42") // a space before the digits
    fmt.Println(second, err)
}
0 strconv.Atoi: parsing "42abc": invalid syntax
0 strconv.Atoi: parsing " 42": invalid syntax

Atoi needs the whole string to be a number. Even one space breaks it, so trim input first.

Q12. What does this program print with go run . red green?

package main

import (
    "fmt"
    "os"
)

// main counts the words after the program name and prints them
func main() {
    fmt.Println(len(os.Args) - 1) // minus 1 because item 0 is the program path
    fmt.Println(os.Args[1:])      // [1:] means "from item 1 to the end"
}
2
[red green]

os.Args has three items, the program path plus two words. So len(os.Args) - 1 gives the real count of 2.

Q13. What is the difference between os.Args and the flag package?

os.Args gives you raw words in order. The flag package reads named options, sets defaults and prints help with -h. Use flag for any tool other people will run.

Q14. How do you read a float from input?

Use fmt.Scan(&price) with a float64 variable. With a line reader, use strconv.ParseFloat(text, 64) instead.

Q15. What does this program print?

package main

import "fmt"

// main reads two numbers separated by a comma from a string
func main() {
    var first, second int
    count, _ := fmt.Sscanf("7,8", "%d,%d", &first, &second)
    fmt.Println(count, first*second)
}
2 56

The comma in the format matches the comma in the text. So both numbers are read, and 7 times 8 is 56.

Q16. How do you read a password without showing it?

The standard library has no hidden input. The usual choice is term.ReadPassword from the golang.org/x/term module. It turns off the echo while the user types.

Q17. How do you read input fast in a coding test?

Wrap standard input with bufio.NewReader or bufio.Scanner, and wrap output with bufio.NewWriter(os.Stdout). Remember to call Flush on the writer at the end, or some output is lost.

Q18. Can the Go Playground read user input?

No. The Playground has no standard input, so fmt.Scan gets io.EOF at once. Use Sscan on a fixed string, or an online compiler with an input box, to test these programs.

Practice Task

This task mixes two kinds of Go user input. Write a program that reads a student’s name on the first line and three marks on the second line. Then print the total and the average with one decimal place. Hint: read the name with bufio.Reader, then use fmt.Sscan on the second line.

Official Resources

Quick Recap

  • Go user input comes from standard input, command line arguments or pipes.
  • fmt.Scan reads words and converts types, but stops at spaces.
  • bufio.Reader and bufio.Scanner read whole lines and handle big input fast.
  • strconv.Atoi turns text into numbers and reports bad input.
  • os.Args and the flag package read values from the command line.

What’s Next?

Now that your programs can read numbers, let’s do real calculations with them. Read Go basic math programs with output. For a refresher on the operators we use there, see Go operators explained with examples.