dongsou4301 2017-05-08 08:53
浏览 632
已采纳

Golang中的Scanln不接受空格

How can I use Scanln that accepts whitespace as input?

  • 写回答

1条回答 默认 最新

  • drn1008 2017-05-08 09:12
    关注

    You can't use the fmt package's Scanln() and similar functions for what you want to do, because quoting from fmt package doc:

    Input processed by verbs is implicitly space-delimited: the implementation of every verb except %c starts by discarding leading spaces from the remaining input, and the %s verb (and %v reading into a string) stops consuming input at the first space or newline character.

    The fmt package intentionally filters out whitespaces, this is how it is implemented.

    Instead use bufio.Scanner to read lines that might contain white spaces which you don't want to filter out. To read / scan from the standard input, create a new bufio.Scanner using the bufio.NewScanner() function, passing os.Stdin.

    Example:

    scanner := bufio.NewScanner(os.Stdin)
    if scanner.Scan() {
        line := scanner.Text()
        fmt.Printf("Input was: %q
    ", line)
    }
    

    Now if you enter 3 spaces and press <kbd>Enter</kbd>, the output will be:

    Input was: "   "
    

    A more complete example that keeps reading lines until you terminate the app or enter "quit", and also checks if there was an error:

    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        line := scanner.Text()
        fmt.Printf("Input was: %q
    ", line)
        if line == "quit" {
            fmt.Println("Quitting...")
            break
        }
    }
    if err := scanner.Err(); err != nil {
        fmt.Println("Error encountered:", err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料