views:

69

answers:

2

In the program written below how i can ensure that only integer value is entered? And if character is entered the program should convert it to its ASCII equivalent and then add them and show output as number. Please help me......

#include<stdio.h>
int main(int argc, char **argv)
{
 int a,b,c;
 printf("enter two numbers:-");
 scanf("%d \t %d",&a,&b);
 c=a+b;
 printf("addition of numbers= %d",c);
}
+1  A: 

scanf returns the number of items that it successfully read, so you can check to make sure that it returns the same number that you expect. For example,

if (scanf("%d \t %d", &a, &b) != 2)
{
    // handle error
}

Note that \t is a whitespace character, and whitespace is ignored by scanf.

James McNellis
thank you for information it is useful for me
Cold-Blooded
A: 

Just to add to what James said.

Dont forget to flush stdin

#include<stdio.h>
int main(int argc, char **argv)
{
 int a,b,c;

 printf("enter two numbers:-");
 if( scanf("%d \t %d",&a,&b)  == 2 )
 {
    c=a+b;
     printf("addition of numbers= %d",c);
 }
 else {
        printf("please enter a valid input");
        getchar(); // the getchar will clear the stdin otherwise next time you go do 
                   // a scanf it might not work. 
    }
}
jramirez
thank you it helped me alot..........
Cold-Blooded
you are welcome
jramirez