Get a valid integer from keyboard.

It will check if there are non digits or too many digits.

https://onlinegdb.com/AvF3_-gE4

/*
Desc: Get a valid integer from keyboard.
It will check if there are non digits or too many digits.
A valid integer may include a sign and at most 9 digits.

Auth: Liutong XU
*/

#include<stdio.h>
#include<stdlib.h>
#define MAXCHARS 81
#define TRUE 1
#define FALSE 0

int getanInt();
int isValidInt(char val[MAXCHARS]);

int main()
{
    int number;

    number = getanInt();
    printf("The number you entered is %d\n", number);

    return 0;
}

int getanInt()
{
    char value[MAXCHARS];
    // typical scenario to use do-while
    do
    {
        printf("Enter an integer, at most 9 digits plus one sign: ");
        fgets(value, MAXCHARS, stdin);
    } while (!isValidInt(value));  
// while NOT valid, re-input. checking with a function return (atoi(value));
// convert a string into a number, or you can write a piece of code to convert } int isValidInt(char val[MAXCHARS]) { int start = 0; int pos; int valid = TRUE; int sign = FALSE; // empty string is NOT valid if (val[0] == '\0' || val[0] == '\n') return FALSE; // we have a sign if (val[0] == '-' || val[0] == '+') { sign = TRUE; start = 1; } // a sign without any digit, invalid if (sign == TRUE && val[1] == '\0' && val[1] == '\n') return FALSE; // now start processing digits pos = start; while (valid == TRUE && val[pos] != '\0' && val[pos] != '\n') { if (val[pos] < '0' || val[pos] > '9') // non-digit valid = FALSE; pos++; } // too many digits CANNOT fit into an int type if (pos - sign > 9) { valid = FALSE; printf("Too many digits..."); } // print a message if (!valid) { printf("Invalid integer\n"); } return valid; }

You have no rights to post comments