multiline input in a terminal Go application -


i need let user input multiline text console.

here code:

package main  import (     "bufio"     "fmt"     "os" )  func main() {     {         fmt.println("how read lines here?")         in := bufio.newreader(os.stdin)         result, err := in.readstring('\n')         if err != nil {             fmt.println(err)         }         fmt.println("\nresult")         fmt.println(result)           } } 

i pasted in console:

    hello     world 

it outputs:

how read lines here?          hello         world   result   how read lines here?  result         hello  how read lines here?  result         world  how read lines here?  result   how read lines here? 

but expect be:

         how read lines here?                  hello                 world           result           how read lines here?          result                 hello                 world          how read lines here? 

i guess need use eof instead of '\n' how exactly?

update

peterso's answer works except in case when trying paste clipboard text 1 or more empty lines in-between, like:

hello  world 

it prints

enter lines: hello  worldresult: hello  enter lines: 

update 2

the great updated peterso's answer works text empty lines.

buffer set of lines , detect end of set of lines. example,

package main  import (     "bufio"     "fmt"     "os" )  func main() {     scn := bufio.newscanner(os.stdin)     {         fmt.println("enter lines:")         var lines []string         scn.scan() {             line := scn.text()             if len(line) == 1 {                 // group separator (gs ^]): ctrl-]                 if line[0] == '\x1d' {                     break                 }             }             lines = append(lines, line)         }          if len(lines) > 0 {             fmt.println()             fmt.println("result:")             _, line := range lines {                 fmt.println(line)             }             fmt.println()         }          if err := scn.err(); err != nil {             fmt.fprintln(os.stderr, err)             break         }         if len(lines) == 0 {             break         }     } } 

console:

 enter lines: hello world ^]  result: hello world  enter lines: farewell  world  ^]  result: farewell  world   enter lines: ^] 

to terminate set of lines, on empty line, enter: <ctrl+]><enter>. terminate input, enter single line: <ctrl+]><enter>.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -