fork download
  1. /*
  2. Desc: Get a valid integer from keyboard.
  3. It will check if there are non digits or too many digits.
  4. A valid integer may include a sign and at most 9 digits.
  5.  
  6. Auth: Liutong XU
  7. Date: 2017.12.16
  8. */
  9.  
  10. #include<stdio.h>
  11. #include<stdlib.h>
  12. #define MAXCHARS 81
  13. #define TRUE 1
  14. #define FALSE 0
  15. int getanInt();
  16. int isValidInt(char val[MAXCHARS]);
  17. int main()
  18. {
  19. int number;
  20.  
  21. number = getanInt();
  22.  
  23. printf("The number you entered is %d\n", number);
  24. return 0;
  25. }
  26.  
  27. int getanInt()
  28. {
  29. int isanInt = FALSE;
  30. char value[MAXCHARS];
  31.  
  32. do
  33. {
  34. printf("Enter an integer, at most 9 digits plus one sign: ");
  35. fgets(value, MAXCHARS, stdin);
  36.  
  37. int i = 0;
  38. while (value[i]!='\n' && i < 11) i++; //11th char is invalid if any
  39. value[i] = '\0';
  40.  
  41. isanInt = isValidInt(value);
  42. if (!isanInt)
  43. {
  44. printf("Invalid integer\n");
  45. }
  46. } while (!isanInt);
  47.  
  48. return (atoi(value));
  49. }
  50.  
  51. int isValidInt(char val[])
  52. {
  53. int start = 0;
  54. int i;
  55. int valid = TRUE;
  56. int sign = FALSE;
  57.  
  58. if (val[0] == '\0') valid = FALSE;
  59. if (val[0] == '-' || val[0] == '+')
  60. {
  61. sign = TRUE;
  62. start = 1;
  63. }
  64. if (sign == TRUE && val[1] == '\0') valid = FALSE;
  65.  
  66. i = start;
  67. while (valid == TRUE && val[i] != '\0')
  68. {
  69. if (val[i] < '0' || val[i] > '9')
  70. valid = FALSE;
  71. i++;
  72. }
  73. if (i - sign > 9)
  74. {
  75. valid = FALSE;
  76. printf("Too many digits...");
  77. }
  78.  
  79. return valid;
  80. }
Success #stdin #stdout 0s 4292KB
stdin
+987654321
stdout
Enter an integer, at most 9 digits plus one sign: The number you entered is 987654321