Hossein Safari
Hossein Safari

Reputation: 369

How to read a string with fmt.Scan after using bufio for reading a line in Go?

I read a line with bufio.NewReader(os.Stdin), then I read a string with fmt.Scanf.

package main

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

func main() {
    reader := bufio.NewReader(os.Stdin)
    
    var str string
    inp, _ := reader.ReadString('\n')
    fmt.Scanf("%s", &str)
    
    fmt.Println(inp)
    fmt.Printf(str)
}

Input:

This is a sentence.
John

I expect the output to be like above, but it isn't.
Output:

This is a sentence.

actually fmt.Scanf("%s", &str) doesn't work.
What is the problem? and How can I fix it?

Upvotes: 1

Views: 900

Answers (1)

Mike Shum
Mike Shum

Reputation: 382

reader.ReadString(delim) reads everything up to the delim, including the delimiter. So, it adds \n between two inputs. fmt.Printf(str) does not have \n in the end, so the second output sticks to the next thing printed to stdout.

package main

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

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

    var str string
    inp, _ := reader.ReadString('\n')
    fmt.Scanf("%s", &str)

    fmt.Println(inp)
    fmt.Printf(str)
}

Input:

some line
John

Output:

some line

John

Below is the code that runs as you want it to.

   package main

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

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

    var str string
    inp, _ := reader.ReadString('\n')
    fmt.Scanf("%s", &str)

    fmt.Print(inp)
    fmt.Printf("%s\n", str)
}

enter image description here

Upvotes: 1

Related Questions