-1

I have an application which gets 10 different numbers (which are less than 100) as input. If any thing other than number is entered, it should display "Invalid input"

ex: If I enter 'C' which is not a number between 1 to 100, Program should display "Invalid input"

I don't want to compare the input with all the characters and special symbols

If the number is a single digit number, isdigit() or isalpha() does the job.

How can I solve this?

Durgesh Tanuku
  • 1,124
  • 2
  • 10
  • 26
  • 1
    take the input as a string, f.e. `"65"` or `"C"` and run your isdigit-check on the string until reaching not a digit or the end of the string. – Peter Miehle Feb 24 '15 at 11:26

3 Answers3

3

I would just use something like this: scanf("%d", &variable) and check return value of this function. It will work unless you have something other than digit on stdin. You can put this in the loop and catch this error using return value of scanf() function.

Community
  • 1
  • 1
newfolder
  • 108
  • 2
  • 9
2

If the number is a single digit number, isdigit() or isalpha() does the job.

But you want to check a number between 1 and 99 (more than one digit), in this case you can use isdigit() in a loop, scanf or strtol:

An example using strtol:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char str[32];
    char *end;
    long num;

    printf("Enter a number between 1 and 99:\n");
    fgets(str, sizeof str, stdin);
    num = strtol(str, &end, 10);
    if ((num < 1) || (num > 99) || (*end != '\n')) {
        printf("Error\n");
    } else {
        printf("%ld\n", num);
    }
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
-1

I suppose you get the numbers in a loop right? If it is, you can add an if-statement to control the inserted values.

if (num>=0 && num <=100)
//code
else
printf("Invalid input");

And you insert this code in the loop after the scanf("%d",&variable) function.

sentientmachine
  • 347
  • 3
  • 14
  • -1: UB when the input is not a number (question explicitly asks about this case); errors going to stdout and without a newline (also negatively impacts buffering behaviour); question says "less than 100" (i.e. excluding 100) and "between 1 and 100" (excluding 0) so your check is off-by-one on both sides. – Score_Under Jul 25 '15 at 19:27