[Go]Get user’s input string

There are several ways to get the input string.
The first method is to use bufioNewReader(os.Stdin) to read the stdin, using the reader object get the user input from stdin until a delimiter is input by user, the entire string includes the delimiter enter by user.

First method, use bufio to get stdin

package main

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

func main() {
	// Create reader object.
	reader := bufio.NewReader(os.Stdin)
	fmt.Println("Enter your input:")
	// Read until the delimiter string, the whole string read includes the delimiter.
	// Take note that it is a single quotes not double quotes.
	// double quotes is for string.
	// single quote is the rune of the string which is an ascii number representation.
	// ReadString takes in a byte not a string.
	text,_ := reader.ReadString('\n')
	fmt.Println("Your input text is:", text)
}

Second method use bufio.NewScanner
this is an infinite loop to get user’s input until the program breaks from ctrl+c.

package main

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

func main() {
	fmt.Println("Type in any text:")
	scanner := bufio.NewScanner(os.Stdin)
	// scanner.Scan() returns a boolean.
	// this is the same as while true.
	// which is an infinite loop until you press ctrl+c to break it.
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
}

Third method is to use the fmt.Scan()
This method uses fmt.Scan() the memory address that points to string variable is passed into Scan(), the stdin will be stored into this variable. The string stored will be terminated at white space, hence this method can only get a word not a sentence that has white spaces.

package main

import (
	"fmt"
	"log"
)

func main() {
	var s string
	fmt.Println("Type anything:")
	if _, err := fmt.Scan(&s); err != nil {
		log.Fatal(err)
	}
	fmt.Println(s)
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s