Consider this Go program that reads a single word from the user and prints it back:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('\n')
fmt.Print(input)
}If the user types hello and presses Enter, what will be printed?
package main import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) input, _ := reader.ReadString('\n') fmt.Print(input) }
Think about what ReadString('\n') includes in the returned string.
The ReadString('\n') method reads input until it finds a newline character, and includes that newline in the returned string. So the output will be hello\n.
Look at this Go code snippet:
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scanln(&name)
fmt.Println("Hello,", name)
}If the user types John Doe and presses Enter, what will be printed?
package main import "fmt" func main() { var name string fmt.Print("Enter your name: ") fmt.Scanln(&name) fmt.Println("Hello,", name) }
Remember how Scanln reads input and stops at spaces.
fmt.Scanln reads input until the first space or newline. So it reads only "John" and stops before "Doe". The output is "Hello, John".
Consider this Go program:
package main
import "fmt"
func main() {
var a, b int
fmt.Print("Enter two numbers: ")
fmt.Scan(&a, &b)
fmt.Println(a + b)
}If the user inputs 3 5 and presses Enter, what will be printed?
package main import "fmt" func main() { var a, b int fmt.Print("Enter two numbers: ") fmt.Scan(&a, &b) fmt.Println(a + b) }
Think about how fmt.Scan parses multiple inputs separated by spaces.
fmt.Scan reads two integers separated by space and stores them in a and b. Then it prints their sum, which is 8.
Look at this Go code:
package main
import "fmt"
func main() {
var x int
fmt.Print("Enter a number: ")
_, err := fmt.Scanf("%d", &x)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("You entered", x)
}
}If the user types hello and presses Enter, what will be printed?
package main import "fmt" func main() { var x int fmt.Print("Enter a number: ") _, err := fmt.Scanf("%d", &x) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("You entered", x) } }
What happens if you try to scan a string into an integer variable?
fmt.Scanf returns an error if the input cannot be converted to the variable type. Here, scanning "hello" into an int causes an input mismatch error.
Which statement best describes the difference between using bufio.Reader.ReadString('\n') and fmt.Scanln for reading input in Go?
Think about how each method treats spaces and newlines in input.
bufio.Reader.ReadString('\n') reads the full line including spaces and the newline character. fmt.Scanln reads input until the first space or newline, so it stops early if spaces appear.