Handling stdin in Go: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 6: Line 6:
==<tt>fmt.Scan()</tt>==
==<tt>fmt.Scan()</tt>==
{{External|https://golang.org/pkg/fmt/#Scan}}
{{External|https://golang.org/pkg/fmt/#Scan}}
Read text from <code>stdin</code>, storing 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, <tt>err</tt> will report why.
Read text from <code>stdin</code>, '''storing 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, <tt>err</tt> will report why.
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
var s string
var s string
Line 12: Line 12:
fmt.Printf("input line: %s, cnt: %d, error: %s\n", s, cnt, err)
fmt.Printf("input line: %s, cnt: %d, error: %s\n", s, cnt, err)
</syntaxhighlight>
</syntaxhighlight>
==<tt>fmt.Scanln()</tt>==
==<tt>fmt.Scanln()</tt>==
{{External|https://golang.org/pkg/fmt/#Scanln}}
{{External|https://golang.org/pkg/fmt/#Scanln}}

Revision as of 02:03, 23 August 2023

Internal

Handling stdin with fmt Functions

fmt.Scan()

https://golang.org/pkg/fmt/#Scan

Read text from stdin, storing 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()

https://golang.org/pkg/fmt/#Scanln

Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

var line string
fmt.Scanln(&line)

fmt.Scanf()

https://golang.org/pkg/fmt/#Scanf
var f float
cnt, err := fmt.Scanf("%f", &f)