'How to make program wait for further input?

If I run the below program and enter an answer (e.g. "3 years") the program completes without waiting for any further input e.g.:

How long did the christians walk for the crusade? :3 years
Correct!
How many of the crusades were won by christians? :Incorrect.
Who started the crusades? :Incorrect.
Thank you for playing!

How can I make it wait for answers to the other questions?

package main

import (
    "bufio"
    "fmt"
    "os"
    "time"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Printf("How long did the christians walk for the crusade? :")
    scanner.Scan()
    input := scanner.Text()

    if input == "3 years" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("How many of the crusades were won by christians? :")

    if input == "1" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("Who started the crusades? :")

    if input == "the pope" {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }

    fmt.Printf("Thank you for playing!")
    time.Sleep(2 * time.Hour)
}
go


Solution 1:[1]

scanner.Scan()
input := scanner.Text()

The above will accept a single line of input and store the result in the variable input.

So when your program runs it asks the first question and waits for an answer; lets say I answer with "1 day" then input == "1 day". The value of Input is not changed after that point - you are comparing the first value the user enters against multiple answers i.e. "1 day" == "3 years" and "1 day" == "the pope".

If you want to accept additional lines you will need to repeat the call e.g.

scanner.Scan()
input := scanner.Text()

if input == "3 years" {
    fmt.Println("Correct!")
} else {
    fmt.Println("Incorrect.")
}

fmt.Printf("How many of the crusades were won by christians? :")
scanner.Scan() // Get next answer from scanner
input = scanner.Text()

if input == "1" {
    fmt.Println("Correct!")
} else {
    fmt.Println("Incorrect.")
}

Note that you can simplify this considerably by using a function:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    s := bufio.NewScanner(os.Stdin)

    askQuestion(s, "How long did the christians walk for the crusade? :", "3 years")
    askQuestion(s, "How many of the crusades were won by christians? :", "1")
    askQuestion(s, "Who started the crusades? :", "the pope")

    fmt.Printf("Thank you for playing!")
}

func askQuestion(s *bufio.Scanner, question string, answer string) {
    fmt.Print(question)
    if !s.Scan() {
        panic(fmt.Sprintf("scan failed: %s", s.Err()))
    }
    if s.Text() == answer {
        fmt.Println("Correct!")
    } else {
        fmt.Println("Incorrect.")
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1