Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int nfields, num;
- char dummy[2];
- fputs("Please enter a decimal integer: ", stdout);
- fflush(stdout);
- nfields = scanf("%d%1[^\n]", &num, dummy);
- while (nfields != 1)
- {
- puts("Invalid input! Please try again.");
- fputs("Enter a decimal integer (and nothing else): ", stdout);
- fflush(stdout);
- /* Consume remaining line of input. */
- while (0 != scanf("%*[^\n]"))
- ;
- nfields = scanf("%d%1[^\n]", &num, dummy);
- }
- printf("num = %d\n", num);
- /*
- This code first prompts for a number, then attempts to read in two
- fields: a decimal integer and a single character that is not a newline
- (as indicated by the %1[^\n] conversion specifier). However, we want it
- to fail to read the second field. There are several scenarios that can
- be encountered:
- 1) no fields are read in, meaning there are no digits at the start of
- the input, scanf() returns 0, and we enter the loop to try again (after
- consuming the remaining line of input so we don't get stuck in an
- endless loop);
- 2) a numerical field and an extra character field are read in, meaning
- there are digits at the start of the input but there is some non-digit
- character(s) after that, scanf() returns 2, and the loop is entered to
- try again;
- 3) a numerical field is read, but no other characters are present, and
- scanf() returns 1, meaning that only digits were entered, which is what
- we want, so we don't enter the loop.
- The last printf() statement then tells us what number was entered.
- */
Advertisement
Add Comment
Please, Sign In to add comment