This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

The problem

The Go input for Scan, whether Scanf, Scanln, or whatever, ends with a space.

But our input may be blank.

For example, Fan One 666, at which point we know the Go language, and when we accept this Fan, we stop.

  • Scan
var msg string
_,_ =fmt.Scan(&msg)
fmt.Printf(msg)
Copy the code

The input

Fan One 666
Copy the code

The output

Fan
Copy the code

  • Scanf
var msg string
_,_ =fmt.Scanf("%s",&msg)
fmt.Printf(msg)
Copy the code

The input

Fan One 666
Copy the code

The output

Fan
Copy the code

  • Scanln
var msg string
_,_ =fmt.Scanln(&msg)
fmt.Printf(msg)
Copy the code

The input

Fan One 666
Copy the code

The output

Fan
Copy the code

You can see this is true for all three of them, and the space completes the typing

So very uncomfortable ah!! Unable to output 666!!

But there is a solution! Since scan does not work, we can change other I/O streams!

To solve

Then we can’t use Scan and switch to Bufio’s standard I/O format

Bufio.NewReader is a function in the bufio package that reads strings to bufio.NewReader.

The following code

var msg string
reader := bufio.NewReader(os.Stdin) // Standard input/output
msg,_ = reader.ReadString('\n')  // Press Enter to end
msg = strings.TrimSpace(msg)    // remove the last space
fmt.Printf(msg)
Copy the code

The input

Fan One 666
Copy the code

The output

Fan One 666
Copy the code

Problem solved.

The last

Xiao Sheng Fan Yi, looking forward to your attention.