You can now convert text and take a line apart. The last piece is getting the lines into the program in the first place. Standard input, or stdin, is text supplied to a program. The stdin box under the editor is already filled in; edit it before pressing Run. A bufio.Scanner on os.Stdin reads one line at a time. scanner.Scan() returns false at the end of the input or on an error, so check scanner.Err() after the loop. scanner.Text() gives the current line without its newline.
Predict and run
How many lines does the scanner visit?
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("Input error:", err)
}
}Check your prediction
Poems
EssaysAdd a third line without a final newline. Predict whether it is read.
Where stdin comes from
Every program starts with three standard streams: standard input for reading, and standard output and standard error for writing. fmt.Println writes to standard output. In a terminal, standard input is whatever the person types. It can also come from a file, as in go run . < sample.txt, which is how you can run the reading log on your own computer on Day 7. (Windows PowerShell does not accept <; Day 7 shows the alternative.) The program reads the same way in every case, which is why stdin is such a convenient way to feed it data. In this editor, the stdin box plays the role of the file.
The scanning loop
The loop has three parts, and each matters:
bufio.NewScanner(os.Stdin)creates a scanner that reads from standard input. Thebufiopackage reads input in large chunks behind the scenes, which is much faster than reading one character at a time.for scanner.Scan()is a condition-only loop. Each call toScanmoves to the next line and returnstrue, or returnsfalsewhen there are no more lines.- Inside the loop,
scanner.Text()is the current line as astring, without its trailing newline.
A final line without a newline is still read, and a blank line arrives as the empty string "". Your program has to decide what a blank line means. For the reading log, it means "skip this line".
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
lineNumber := 0
for scanner.Scan() {
lineNumber++
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
fmt.Printf("Line %d: %s\n", lineNumber, line)
}
if err := scanner.Err(); err != nil {
fmt.Println("Input error:", err)
}
}Line 1: Poems,25
Line 4: Essays,30The counter goes up before the blank check, so line numbers still match what the person sees in their input. That makes an error message such as Line 4: use title,minutes easy to act on.
The if with a short statement
if err := scanner.Err(); err != nil is a new form. The part before the semicolon runs first and declares err; the condition after it is then checked as usual. A variable declared this way exists only inside the if and its else. That keeps a short-lived error from leaking into the rest of the function, so it is the usual way to write a one-off error check.
Why check Err after the loop?
Scan returns false both at a normal end of input and when reading fails, for example when a single line is too long for the scanner's buffer. Only scanner.Err() can tell the two apart. It returns nil after a normal end, so the check costs nothing when all is well.
Practice
Your turn
Print the number of lines in the supplied input. A blank line also counts, so add one to the stdin box and check.
package main
func main() {
// Write your code here.
}Hint 1: the idea
Only count after Scan returns true.
Hint 2: a first step
Create a scanner with bufio.NewScanner(os.Stdin).
Worked solution
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
count := 0
for scanner.Scan() {
count++
}
if err := scanner.Err(); err != nil {
fmt.Println("Input error:", err)
return
}
fmt.Println(count)
}2count changes only inside the loop, after a successful Scan. Empty the stdin box and it prints 0.
Completion is saved in this browser only. It does not measure mastery.