duannuci4008 2014-11-07 23:10
浏览 383

在EOF之前,有没有类似于getchar()的Go函数?

I'm new at Go. I know it has some scanning functions: scan, sscan, scanf, sscanf and others.

but all of them, and I quote : "storing successive space-separated values", some treat new lines as spaces. but this is not I need.

I've already tried this:

reader := bufio.NewReader(os.Stdin)
input, _ := reader.ReadString('
')
fmt.Printf("Input Char Is : %v", string([]byte(input)[0]))

but this stops after new line not EOF.

I need a way to scan single chars one at a time until EOF. in C I would write:

while (getChar()){
//do stuff 
}

What is the equivalent to this in Go?

  • 写回答

1条回答 默认 最新

  • duanhuilao0787 2014-11-07 23:31
    关注

    Two techniques pop to mind:

    1. ioutil.ReadAll

    From the documentation:

    ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.

    For example:

    byteSlice, err := ioutil.ReadAll(os.Stdin)
    if err != nil {
        log.Fatal(err)
    }
    
    for b := range byteSlice {
        // do stuff
    }
    

    This is should not be used for io.Reader that are anything else than files (for example network connections) because an EOF condition may never happen, and so the program may block forever.

    In your case, it is fine to use this technique, especially if you don't mind holding all the bytes in memory.

    2. io.ByteReader

    An alternative is also to use the io.ByteReader interface through a bufio.Reader, like this:

    reader := bufio.NewReader(os.Stdin)
    for {
        b, err := reader.ReadByte()
        if err != nil {
            break
        }
    
        // do stuff
    }
    

    This is the closest to C's getchar() loop.

    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?