Good way to flush scanf buffer when invalid entry entered

前端 未结 3 601
轻奢々
轻奢々 2021-01-23 20:18

I have been thinking of ways to flush bad entries in scanf functions to allow for loop prompts to do their job.

I have a function call here that flushes th

3条回答
  •  生来不讨喜
    2021-01-23 21:07

    There's a few ways of doing this. Effectively, what you're trying to do is consume a line of text up to a \n character (or an EOF.) To do this properly, you should use sscanf (or fscanf.)

    sscanf("%*[^\n]\n");
    

    This uses the regular expression [^\n]*\n (Any number of characters that are NOT \n, followed by a \n) and consumes everything matching that.

    Edit: Because I'm dumb and forgot that scanf regex's use a slightly different syntax.

提交回复
热议问题