Advertisement
Guest User

Untitled

a guest
Jul 21st, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define BUFFERSIZE 10
  6.  
  7. int main() {
  8.  
  9. /* Width is the width of the diamond provided by user.
  10.    Check is a pointer required by strtol() below */
  11.         int width;
  12.         char *check;
  13.  
  14. /* Allocate memory for input string */
  15.         char *input = (char *)malloc(BUFFERSIZE+2);
  16.  
  17. /* Checks to see if malloc() succeeded */
  18.         if(input == NULL) {
  19.                 printf("Error: Failed to allocate memory.\n");
  20.                 return 1;
  21.         }
  22.  
  23.         printf("Enter an integer: ");
  24.  
  25. /* Reads input and checks to see if it's a string. fgets() is better
  26.    than scanf(), which can result in buffer overflows.. */
  27. if(fgets(input, BUFFERSIZE+2, stdin) == NULL) {
  28.         printf("Error: No input given.\n");
  29.         return 1;
  30. }
  31.  
  32. /* Checks to see if input is a number. If so, converts it to an int */
  33.         if(isNumber(input)) {
  34.                 width = strtol(input, &check, 0);
  35.                 if(width < 1) {
  36.                         printf("Error: Input was not a positive integer.\n");
  37.                         return 1;
  38.                 }
  39.                 printf("The width of the integer is %d.\n", width);
  40.         } else {
  41.                 printf("Error: Input was not a positive integer.\n");
  42.         }
  43.  
  44. /* Always deallocate memory, even if this is your entire program */
  45.         free(input);
  46. }
  47.  
  48. /* Returns 1 if input is an integer; returns 0 otherwise. */
  49.  
  50. int isNumber(char *input) {
  51.         int i;
  52.         for(i = 0; input[i] != '\0'; i++) {
  53.                 if(isalpha(input[i]))
  54.                         return 0;
  55.                 else
  56.                         return 1;
  57.         }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement