reader.ReadString does not strip out the first occurrence of delim

前端 未结 4 1177
执念已碎
执念已碎 2020-12-07 04:27

I wrote a simple go program and it isn\'t working as it should:

package main

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

func main() {
    reader := bu         


        
相关标签:
4条回答
  • 2020-12-07 04:52
    reader.ReadLine() 
    

    Can leave ‘\n’ but reader.ReadString() can't

    0 讨论(0)
  • 2020-12-07 05:05

    This is because your the text is storing Bob\n

    One way to solve this is using strings.TrimSpace to trim the newline, eg:

    import (
        ....
        "strings"
        ....
    )
    
    ...
    if aliceOrBob(strings.TrimSpace(text)) {
    ...
    

    Alternatively, you can also use ReadLine instead of ReadString, eg:

    ...
    text, _, _ := reader.ReadLine()
    if aliceOrBob(string(text)) {
    ...
    

    The reason why the string(text) is needed is because ReadLine will return you byte[] instead of string.

    0 讨论(0)
  • 2020-12-07 05:07

    I think the source of confusion here is that:

    text, _ := reader.ReadString('\n')
    

    Does not strip out the \n, but instead keeps it as last value, and ignores everything after it.

    ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter.

    https://golang.org/src/bufio/bufio.go?s=11657:11721#L435

    And then you end up comparing Alice and Alice\n. So the solution is to either use Alice\n in your aliceOrBob function, or read the input differently, as pointed out by @ch33hau.

    0 讨论(0)
  • 2020-12-07 05:10

    I don't know anything about Go, but you might want to strip the string of leading or trailing spaces and other whitespace (tabs, newline, etc) characters.

    0 讨论(0)
提交回复
热议问题