X
X
xotkot2015-05-22 13:43:38
go
xotkot, 2015-05-22 13:43:38

How to correctly read the input of a string with spaces in the console?

in general, the essence of the question is stated in the heading
fmt.Scan* reads word by word (
p.s.
SOLUTION
Below is an example with two simple functions for reading a line (with spaces) in the console, based on the answers :

package main

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

func Scan1() string {
  in := bufio.NewScanner(os.Stdin)
  in.Scan()
  if err := in.Err(); err != nil {
    fmt.Fprintln(os.Stderr, "Ошибка ввода:", err)
  }
  return in.Text()
}

func Scan2() string {
  in := bufio.NewReader(os.Stdin)
  str, err := in.ReadString('\n')
  if err != nil {
    fmt.Println("Ошибка ввода: ", err)
  }
  return str
}

func main() {
  fmt.Println("LINE1 : ", Scan1())
  fmt.Println("LINE2 : ", Scan2())
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2015-05-22
@xotkot

As SilentFl already noted , it is correct to use bufio .

myscanner := bufio.NewScanner(os.Stdin)
myscanner.Scan()
line := myscanner.Text()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question