I have this code:
var scanner = bufio.NewScanner(os.Stdin)
func readInt() int {
scanner.Scan()
ans, _ := strconv.Atoi(scanner.Text())
return ans
}
func main() {
scanner.Split(bufio.ScanWords)
n := readInt()
fmt.Println(n)
}
Now, the scanner
variable is global. And I want to make it local and pass it to readInt()
function as a parameter. When I tried this way it would not work:
func readInt(scanner bufio.NewScanner) int {
scanner.Scan()
ans, _ := strconv.Atoi(scanner.Text())
return ans
}
func main() {
var scanner = bufio.NewScanner(os.Stdin)
scanner.Split(bufio.ScanWords)
n := readInt(scanner)
fmt.Println(n)
}
If someone could give a hand.
bufio.NewScanner
is a function for creating a new scanner:
func NewScanner(r io.Reader) *Scanner
NewScanner returns a new Scanner to read from r. The split function defaults to ScanLines.
not a type that you can use in a function signature. However, bufio.NewScanner
returns a *bufio.Scanner
and bufio.Scanner
is a type so you could say:
func readInt(scanner *bufio.Scanner) int {
//...
}