views:

82

answers:

2

i have a c program in which i am accepting 2 numbers as input. How do i validate if input entered is numbers only and not characters.

void main()
{
  int a,b;
  printf("Enter two numbers :");
  scanf("%d%d",&a,&b);
  printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}

[Edit] Added Sample Code

+2  A: 

scanf returns the number of items that it has successfully scanned. If you asked for two integers with %d%d, and scanf returns 2, then it successfully scanned both numbers. Any number less than two indicates that scanf was unable to scan two numbers.

int main()
{
    int a,b;
    int result;

    printf("Enter two numbers :");
    result = scanf("%d%d",&a,&b);

    if (result == 2)
    {
        printf("Number 1 is : %d \n Number 2 is : %d",a,b);
    }
    else if (result == 1)
    {
        // scanf only managed to scan something into "a", but not "b"
        printf("Number 1 is : %d \n Number 2 is invalid.\n", a);
    }
    else if (result == 0)
    {
        // scanf could not scan any number at all, both "a" and "b" are invalid.
        printf("scanf was not able to scan the input for numbers.");
    }
}

One other value that scanf may return is EOF. It may return this if there is an error reading from the stream.

Also note that main returns int, but you have it declared with void return.

dreamlax
+2  A: 

Besides the other interesting suggestions (especially the one with scanf), you might also want to use the isdigit function:

The isdigit() function shall test whether c is a character of class digit in the program's current locale

note that this function examines only ONE char, not an entire bunch of them.

It is always good practice to resort to already-built functions; there are intricacies you might not be aware of even in the simplest task, and this will make you a good programmer overall.

Of course, in due time you might want to look at how that function works to get a good grasp of the underlying logic.

lorenzog
+1, but it's worth noting that `isdigit` only works on individual characters, not entire strings, so this would require testing input character-by-character.
dreamlax
@dreamlax yes, I should have pointed it out better. Have edited the question accordingy. Thanks
lorenzog