Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define BUFFERSIZE 10
- int main() {
- /* Width is the width of the diamond provided by user.
- Check is a pointer required by strtol() below */
- int width;
- char *check;
- /* Allocate memory for input string */
- char *input = (char *)malloc(BUFFERSIZE+2);
- /* Checks to see if malloc() succeeded */
- if(input == NULL) {
- printf("Error: Failed to allocate memory.\n");
- return 1;
- }
- printf("Enter an integer: ");
- /* Reads input and checks to see if it's a string. fgets() is better
- than scanf(), which can result in buffer overflows.. */
- if(fgets(input, BUFFERSIZE+2, stdin) == NULL) {
- printf("Error: No input given.\n");
- return 1;
- }
- /* Checks to see if input is a number. If so, converts it to an int */
- if(isNumber(input)) {
- width = strtol(input, &check, 0);
- if(width < 1) {
- printf("Error: Input was not a positive integer.\n");
- return 1;
- }
- printf("The width of the integer is %d.\n", width);
- } else {
- printf("Error: Input was not a positive integer.\n");
- }
- /* Always deallocate memory, even if this is your entire program */
- free(input);
- }
- /* Returns 1 if input is an integer; returns 0 otherwise. */
- int isNumber(char *input) {
- int i;
- for(i = 0; input[i] != '\0'; i++) {
- if(isalpha(input[i]))
- return 0;
- else
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement