Checking the stdin buffer if it's empty

前端 未结 4 1562
名媛妹妹
名媛妹妹 2020-12-01 22:18

I am trying to read a number character with character, but I don\'t know if the stdin buffer is empty or not.

My first solution whas to look for \'\\n\' character i

4条回答
  •  时光说笑
    2020-12-01 22:31

    There are several soutions:

    poll or select with timeout of 0 - these would return immediately and result is either -1 with errno EAGAIN if no data available or number of descriptors with data (one, since you're checking only stdin).

    ioctl is a swiss army knife of using descriptors. The request you need is I_NREAD:

    if (ioctl(0, I_NREAD, &n) == 0 && n > 0)
        // we have exactly n bytes to read
    

    However the correct solution is to read everything you got (using scanf) as a line, then process the result - and this works good enough with sscanf:

    char buf[80]; // large enough
    scanf("%79s", buf); // read everything we have in stdin
    if (sscanf(buf, "%d", &number) == 1)
        // we have a number
    

    ... as long as you properly handle re-reading, strings that are longer than your buffer, and other real-life complications.

    Edit: removed feof since it is actually used for other things.

提交回复
热议问题