• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

User Input (bufio) in Go

April 28, 2022 Go

In this post, you will learn how to work with the user input (bufio) so that you can use that same knowledge and thus evolve.

  • the bufio library in conjunction with the function NewReader() and the function ReadString() have as main objective “extract” information given by the user;
  • in short, this same junction serves to increase interaction with it;
package main

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

func main() {
	userInput := bufio.NewReader(os.Stdin)

	fmt.Print("Enter your first name: ")
	firstName, _ := userInput.ReadString('\n')

	fmt.Print("Enter your last name: ")
	lastName, _ := userInput.ReadString('\n')

	fmt.Print("Enter your age: ")
	age, _ := userInput.ReadString('\n')

	/*
		CR+LF -> \r\n
		CR -> \r
		LF -> \n
	*/

	fmt.Printf("Name: %s %s\nAge: %s",
						 strings.ReplaceAll(firstName, "\r\n", ""),
						 strings.ReplaceAll(lastName, "\r\n", ""),
						 strings.ReplaceAll(age, "\r\n", ""))

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved