Flushing stdin after every input - which approach is not buggy?

前端 未结 5 510
执笔经年
执笔经年 2020-12-06 07:44

After Mark Lakata pointed out that the garbage isn\'t properly defined in my question I came up with this. I\'ll keep this updated to avoid confusions.


5条回答
  •  温柔的废话
    2020-12-06 08:08

    The first two are subtly different: they both read and ignore all the characters up to a new-line. Then the first skips all consecutive white space so after it executes, the next character you read will be non-whitespace.

    The second reads and ignores characters until it encounters a new-line then reads (and discards) exactly one more character.

    The difference will show up if you have (for example) double-spaced text, like:

    line 1
    
    line 2
    

    Let's assume you read to somewhere in the middle of line 1. If you then execute the first one, the next character you read in will be the 'l' on line 2. If you execute the second, the next character you read in will be the new-line between line 1 and line 2.

    As for the third, if I were going to do this at all, I'd do something like:

    int ch;
    while ((ch=getchar()) != EOF && ch != '\n')
        ;
    

    ...and yes, this does work correctly -- && forces a sequence point, so its left operand is evaluated first. Then there's a sequence point. Then, if and only if the left operand evaluated to true, it evaluates its right operand.

    As for performance differences: since you're dealing with I/O to start with, there's little reasonable question that all of these will always be I/O bound. Despite its apparent complexity, scanf (and company) are usually code that's been used and carefully optimized over years of use. In this case, the hand-rolled loop may be quite a bit slower (e.g., if the code for getchar doesn't get expanded inline) or it may be about the same speed. The only way it stands any chance of being significantly faster is if the person who wrote your standard library was incompetent.

    As far maintainability: IMO, anybody who claims to know C should know the scan set conversion for scanf. This is neither new nor rocket science. Anybody who doesn't know it really isn't a competent C programmer.

提交回复
热议问题