0

I have a function (in C) that gets input from the user, (using scanf) stores it in an unsigned int, and returns the input to other functions that handle it:

unsigned
int input(void)
{
    unsigned int uin;

    scanf("%u", &uin);
    return val;
}

I was wondering, being as I ought to flush stdin, I'd want to use a while loop using getc, vis-a-vis:

while (getc != '\n') {
   ...
}

But, I'm not sure of how to:

A) Do operations inside of getc, as in how I ought to handle checks and concatenate the value, to each character gotten, or, whether or not I'm to getc, and then concatenate from there, removing scanf entirely.

B) Whether this is even the most proper way to do this.

Could some kind person give me some tips and pointers :)

Thanks.

stdinflush
  • 1
  • 1
  • 1

1 Answers1

4

I'd add %*[^\n] to the end of the scanf format string. The * means it should read but ignore the matching input, and the [^\n] means anything but a newline, just like in a regex.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • That's it?! Wow, hehe, I thought I'd have to add some whizzbang but: unsigned int function(void) { unsigned int x; scanf("%*[^\n]u", &x); return x; } Should work, no? – stdinflush Oct 21 '09 at 01:03
  • No -- you add that to the *end* of the format string you already had. – Jerry Coffin Oct 21 '09 at 02:20
  • @stdinflush not that it matters, but just as an fyi, `unsigned` is the same as `unsigned int` (the same way `short` means `short int`). – RastaJedi May 10 '16 at 01:08