Reading input (stdin)
Read what you type in the IDE's Input tab with fmt.Fscan or line by line with bufio.Scanner.
Runs in Zerethon IDE · Go 1.27
Official Go documentation ↗
A run cannot ask questions while it runs. Type the program's input in the Input tab before you press Run; the program reads it from os.Stdin.
main.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
var name string
var a, b int
fmt.Fscan(in, &name)
fmt.Fscan(in, &a, &b)
fmt.Printf("Hello, %s! %d + %d = %d\n", name, a, b, a+b)
}
Input (stdin)
Ada 3 4
Output
Hello, Ada! 3 + 4 = 7
main.go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
total := 0
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
n, err := strconv.Atoi(line)
if err != nil {
fmt.Println("skipped", line)
continue
}
total += n
}
fmt.Println("total:", total)
}
Input (stdin)
5 10 x 15
Output
skipped x total: 30
fmt.Fscanreads values separated by spaces or newlines into the variables you point it to (&name).- Wrap
os.Stdinin onebufio.Readerand keep using it; mixing it with plainfmt.Scanloses buffered input. - When the input runs out,
Fscanreturns an error (EOF) and leaves the variables at their zero value — check its error when the input may be missing.