Write to bufio Scanner from outside os.Stdin

91 views
Skip to first unread message

Mark Bauermeister

unread,
May 29, 2019, 1:26:58 PM5/29/19
to golang-nuts
I'm in the process of writing a text adventure parser.
By default, the parser simply uses Stdin.

i e 

for {
        fmt.Print(">>> ")

        reader := bufio.NewScanner(os.Stdin)
        for reader.Scan() {
            switch reader.Text() {
...
...

This is quite convenient. However, I now want to be able to pass in text from outside this for-loop. Say I have a function "Invoke(arg string)" which I should be able to call to pass
arguments straight to the Scanner interface.

What would be the most straightforward way to achieve this?

roger peppe

unread,
May 29, 2019, 1:38:20 PM5/29/19
to Mark Bauermeister, golang-nuts
https://golang.org/pkg/strings/#NewReader should do what you require.
 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/b34d4bea-d819-4832-9ebd-db11709d6b0c%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Mark Bauermeister

unread,
May 29, 2019, 2:10:46 PM5/29/19
to golang-nuts
Thanks!

I've changed the code to this:

var console *bufio.ReadWriter
var cmd string

func (g *Game) Parse() {
    // reader should be wrapped inside an _input() function.

            for {
        console = bufio.NewReadWriter(
            bufio.NewReader(os.Stdin),
            bufio.NewWriter(os.Stdout))
        fmt.Print(">>> ")

        cmd, _ = console.ReadString('\n')
        switch cmd {
...
...

Now my thinking is that I should be able to simply assign "cmd" from anywhere outside the loop
followed by a newline character (i e "cmd = "Test \n") and the reader should pick it up as if it was a manual input.

Unfortunately, that doesn't quite seem to work yet.
Reply all
Reply to author
Forward
0 new messages