Handling stdin in Go: Difference between revisions
Jump to navigation
Jump to search
Line 30: | Line 30: | ||
=Handling <tt>stdin</tt> with <tt>bufio.NewReader().ReadString()</tt>= | =Handling <tt>stdin</tt> with <tt>bufio.NewReader().ReadString()</tt>= | ||
<syntaxhighlight lang='go'> | |||
r := bufio.NewReader(os.Stdin) | |||
fmt.Print("please provide a string: ") | |||
s, _ := r.ReadString('\n') | |||
fmt.Println(s) | |||
</syntaxhighlight> |
Revision as of 02:19, 23 August 2023
Internal
Handling stdin with fmt Functions
Reading lines of input from stdin
, as individual strings, with fmt.Scan*
functions is somewhat inconvenient. The library seems to want to tokenize the string and store fragments into different variables. That could be a good pattern if you get used with it, but to read lines "in bulk", use bufio.NewReader().ReadString()
.
fmt.Scan()
Read text from stdin
. It stores successive space-separated values into successive arguments. Newlines count as space. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why.
var s string
cnt, err := fmt.Scan(&s)
fmt.Printf("input line: %s, cnt: %d, error: %s\n", s, cnt, err)
fmt.Scanln()
Scanln
is similar to Scan
, but stops scanning at a newline or EOF. It still uses space as separator, and stores space-separated fragments into successive arguments.
var line string
fmt.Scanln(&line)
fmt.Scanf()
var f float
cnt, err := fmt.Scanf("%f", &f)
Handling stdin with bufio.NewReader().ReadString()
r := bufio.NewReader(os.Stdin)
fmt.Print("please provide a string: ")
s, _ := r.ReadString('\n')
fmt.Println(s)