简体   繁体   中英

C, add statement to check if input is an integer

This is currently what I have, I want to add a statement at the bottom that prints printf("Error");if the data entered isn't a number.

int main() {
    long long number;
    long long ret;
    
    printf("Enter a number between [0 - 4294967295]: ");
    scanf("%lld", &number);
    
    printf("Number is %lld\n", number);
    //if statements to see if number is above/below the range
    if (number < 0) {
        printf("Error: This number is below the range.");
        return -1;
    }
    if (number > 4294967295) {
        printf("Error: This number is above the range.");
        return -1;
    } 
    //this is where I would like to add the statement
    return 0;
}

NOTE: User jwdonahue pointed a better solution using fgets() / sscan() instead.


According to the manual page of scanf :

On success, these functions return the number of input items successfully matched and assigned ; this can be fewer than provided for, or even zero, in the event of an early matching failure.

Since you have one value to read, you retrieve the return value of scanf() first and check it before checking number value:

int read_items;
read_items = scanf("%lld", &number);
if (read_items == 0) {
  printf("Not a number\n");
  return 1; // exit with an error status (!= 0)
}

Also you should check before that if even one value was read, which is described by the manual page:

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs

Hence:

int read_items;
read_items = scanf("%lld", &number);
if (read_items == EOF) {
  printf("No value entered or error occured\n");
  return 1; // exit with an error status (!= 0)
}
if (read_items == 0) {
  printf("Not a number\n");
  return 1; // exit with an error status (!= 0)
}

  
for (i=0;i<length; i++)
        if (!isdigit(input[i]))
        {
            printf ("Entered input is not a number\n");
            exit(1);
        }

isdigit(c) is a function in C which can be used to check if the passed character is a digit or not. It returns a non-zero value if it's a digit else it returns 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM