In the program written below how i can ensure that only integer valu开发者_开发知识库e 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);
}
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
.
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.
}
}
精彩评论