A
Army1987
Is this a good way to discard unread data after scanf()?
while (getchar() != '\n')
;
According to the FAQ scanf always leaves the trailing newline on the input
stream, so there's no risk of discarding any more than needed. (In the best
case, when scanf() correctly works and the user hasn't input spurious data
beside those required in the control string, the loop will only iterate
once.)
(The only problem is if for some reason stdin is a file and it ends. But I
could well use drastic solutions such as
assert(!feof(stdin) && !ferror(stdin));
as the loop body, since if a program designed to be interactive reads from a
file which ends we can't do anything better than abort execution.)
--
#include <stdio.h>
#include <stdlib.h>
int main(void) /* Don't try this at home */ {
const size_t dim = 256; int i;
for (i=0; malloc(dim); i++) /*nothing*/ ;
printf("You're done! %zu\n", i*dim);
puts("\n\n--Army1987"); return 0;
}
while (getchar() != '\n')
;
According to the FAQ scanf always leaves the trailing newline on the input
stream, so there's no risk of discarding any more than needed. (In the best
case, when scanf() correctly works and the user hasn't input spurious data
beside those required in the control string, the loop will only iterate
once.)
(The only problem is if for some reason stdin is a file and it ends. But I
could well use drastic solutions such as
assert(!feof(stdin) && !ferror(stdin));
as the loop body, since if a program designed to be interactive reads from a
file which ends we can't do anything better than abort execution.)
--
#include <stdio.h>
#include <stdlib.h>
int main(void) /* Don't try this at home */ {
const size_t dim = 256; int i;
for (i=0; malloc(dim); i++) /*nothing*/ ;
printf("You're done! %zu\n", i*dim);
puts("\n\n--Army1987"); return 0;
}