Search code examples
inputgospace

golang accepting input with spaces


I'm just starting with GO and I understand that SCANF uses spaces as a separator in GO.

fmt.Scanf("%s",&input)

I cant really find a way to accepts inputs that contain spaces as valid characters.


Solution

  • My initial 2014 answer used fmt.Scanln for this specific use case.
    But fmt.Scanln also treats spaces as separators between inputs. That means it cannot directly read an entire line including spaces into a single string variable without additional handling.


    A better option would be to use bufio.NewReader and its ReadString method.
    Unlike fmt.Scanln, bufio.NewReader with ReadString allows you to read an entire line of input, including spaces, into a single string until a newline character is encountered. That behavior is precisely what is needed to accept inputs like "Hello there" as a single string.

    Using fmt.Scanln:        "Hello there" → "Hello"
    Using bufio.NewReader:   "Hello there" → "Hello there"
    

    Using bufio.NewReader to read a line of input, including spaces, until the user presses Enter (newline), would be:

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
        "strings"
    )
    
    func main() {
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Enter text: ")
        input, err := reader.ReadString('\n') // '\n' is the delimiter to stop reading
        if err != nil {
            fmt.Println(err)
            return
        }
    
        // Trim the newline character from the input, if any
        input = strings.TrimSpace(input) 
    
        fmt.Println("You entered:", input)
    }
    

    You can test it on playground go.dev/play.

    Remember, the ReadString method returns the delimiter as part of the input, so you may want to trim the input string to remove the newline character at the end.