Skip to content

Instantly share code, notes, and snippets.

@jeffotoni
Created July 13, 2017 21:20
Show Gist options
  • Select an option

  • Save jeffotoni/437a0ba17f462eb7afc617adf3fc98ec to your computer and use it in GitHub Desktop.

Select an option

Save jeffotoni/437a0ba17f462eb7afc617adf3fc98ec to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
var text string
for text != "q" { // break the loop if text == "q"
fmt.Print("digite algo:")
scanner.Scan()
text = scanner.Text()
if text != "q" {
fmt.Println("seu texto digitado: ", text)
}
}
}
@marcuxyz
Copy link

marcuxyz commented Jul 15, 2017

Você pode fazer desta forma...

package main

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

func main() {
	// faz as perguntas
	pe := perguntas("Digite sua Idade? ", "Digite seu nome? ")

	// obtém o que o usuário digitar
	resp := bufio.NewScanner(os.Stdin)

	// cria um slice de string contedo vazio
	var listaResp = make([]string, 0)

	// faz um for dentro do PE (perguntas), para verificar quantas perguntas tem
	for i := 0; i < len(pe); i++ {
		fmt.Println(pe[1])                         // imprime as perguntas
		resp.Scan()                                // verifica se foi passado alguma entrada de dados, se sim retorna TRUE se não retorna FALSE
		listaResp = append(listaResp, resp.Text()) // adiciona as repostas dentro do slice lsitaResp
	}

	// imprime as respostas
	fmt.Println(listaResp)

}

// armazena as perguntas e retorna um slice contendo todas as perguntas
func perguntas(perguntas ...string) (listaPerguntas []string) {
	for _, perg := range perguntas {
		listaPerguntas = append(listaPerguntas, perg)
	}

	return
}

@marcuxyz
Copy link

marcuxyz commented Jul 15, 2017

Você também pode fazer assim:

package main

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

func main() {

	// obtém o que o usuário digitar
	resp := bufio.NewScanner(os.Stdin)

	for i := 1; i < 6; i++ {
		fmt.Println("Digite algo: ")
		resp.Scan()
		fmt.Printf("Resposta %d =====> %s \n", i, resp.Text())
	}
}

@marcuxyz
Copy link

Dessa forma também funciona:

package main

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

func main() {

	leitura := bufio.NewReader(os.Stdin)

	fmt.Print("Sua Idade? ")

	resposta, _ := leitura.ReadString('\n')

	fmt.Println(resposta)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment