ungetc: number of bytes of pushback

后端 未结 3 1557
闹比i
闹比i 2021-01-13 17:49

ungetc is only guaranteed to take one byte of pushback. On the other hand, I\'ve tested it on Windows and Linux and it seems to work with two bytes.

Are there any pl

3条回答
  •  暖寄归人
    2021-01-13 18:24

    There are some posts here suggesting that it makes sense to support 2 chars for the sake of scanf.

    I don't think this is right: scanf only needs one, and this is indeed the reason for the limit. The original implementation (back in the mid 70s) supported 100, and the manual had a note: in the future we may decide to support only 1, since that's all that scanf needs. See page 3 of the original manual (Maybe not original, but pretty old.)

    To see more vividly that scanf needs only 1 char, consider this code for the %u feature of scanf.

    int c;
    while isspace(c=getc()) {} // skip white space
    unsigned num = 0;
    while isdigit(c)
        num = num*10 + c-'0',
        c = getc();
    ungetc(c);
    

    Only a single call to ungetc() is needed here. There is no reason why scanf needs a char all to itself: it can share with the user.

提交回复
热议问题