Home > Back-end >  How to write the scanner in a separate function to make it work?
How to write the scanner in a separate function to make it work?

Time:09-01

In this code, I have created a function TakeInput() that will take the user input including the whitespaces also. But whenever I run this code and enter the name and school name, it does print the data for me.

Although if I write the scanner without any function, it takes the data with whitespaces.

package main

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

func TakeInput(value string) {
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        value = scanner.Text()
    }

    if err := scanner.Err(); err != nil {
        fmt.Println("Error encountered:", err)
    }
}

func main() {
    var name, school string
    fmt.Printf("Enter your name: ")
    TakeInput(name)

    fmt.Printf("Enter your school name: ")
    TakeInput(school)

    fmt.Println(name, school)
}

CodePudding user response:

Each parameter is a local copy inside the function. You must pass a pointer to TakeInput() (e.g. &name and &school) and modify the pointed value (e.g. *value = scanner.Text(), else you only modify the copy which is discarded upon function return.

For example:

func TakeInput(value *string) {
    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        *value = scanner.Text()
    }

    if err := scanner.Err(); err != nil {
        fmt.Println("Error encountered:", err)
    }
}

func main() {
    var name, school string
    fmt.Printf("Enter your name: ")
    TakeInput(&name)

    fmt.Printf("Enter your school name: ")
    TakeInput(&school)

    fmt.Println(name, school)
}

Also note that bufio.Scanner has an internal buffer. It may read more than what is returned, which when you create a new bufio.Scanner in another TakeInput() call, it may not be able to read previously read, buffered and discarded data.

So create the scanner outside of TakeInput(), e.g.

func TakeInput(scanner *bufio.Scanner, value *string) {
    if scanner.Scan() {
        *value = scanner.Text()
    }

    if err := scanner.Err(); err != nil {
        fmt.Println("Error encountered:", err)
    }
}

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

    var name, school string
    fmt.Printf("Enter your name: ")
    TakeInput(scanner, &name)

    fmt.Printf("Enter your school name: ")
    TakeInput(scanner, &school)

    fmt.Println(name, school)
}

See related / similar questions:

My object is not updated even if I use the pointer to a type to update it

Remove an element of a slice in a struct

  • Related