_aLfa_

scanf an integer

Mar 21st, 2012
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.46 KB | None | 0 0
  1. int nfields, num;
  2. char dummy[2];
  3.  
  4. fputs("Please enter a decimal integer: ", stdout);
  5. fflush(stdout);
  6.  
  7. nfields = scanf("%d%1[^\n]", &num, dummy);
  8. while (nfields != 1)
  9. {
  10.   puts("Invalid input! Please try again.");
  11.   fputs("Enter a decimal integer (and nothing else): ", stdout);
  12.   fflush(stdout);
  13.  
  14.   /* Consume remaining line of input. */
  15.   while (0 != scanf("%*[^\n]"))
  16.   ;
  17.  
  18.   nfields = scanf("%d%1[^\n]", &num, dummy);
  19. }
  20.  
  21. printf("num = %d\n", num);
  22.  
  23. /*
  24. This code first prompts for a number, then attempts to read in two
  25. fields: a decimal integer and a single character that is not a newline
  26. (as indicated by the %1[^\n] conversion specifier). However, we want it
  27. to fail to read the second field. There are several scenarios that can
  28. be encountered:
  29.  
  30. 1) no fields are read in, meaning there are no digits at the start of
  31. the input, scanf() returns 0, and we enter the loop to try again (after
  32. consuming the remaining line of input so we don't get stuck in an
  33. endless loop);
  34.  
  35. 2) a numerical field and an extra character field are read in, meaning
  36. there are digits at the start of the input but there is some non-digit
  37. character(s) after that, scanf() returns 2, and the loop is entered to
  38. try again;
  39.  
  40. 3) a numerical field is read, but no other characters are present, and
  41. scanf() returns 1, meaning that only digits were entered, which is what
  42. we want, so we don't enter the loop.
  43.  
  44. The last printf() statement then tells us what number was entered.
  45. */
Advertisement
Add Comment
Please, Sign In to add comment