How to check input if it is number or not?
I had written a program to check whether input number is even or not. But I don't know how to write a program to check if the input is valid number or not(like character or string)? I tried various method but it didn't work out.So if any one have any program like this or have any idea how to write program please give it to me.
Thanks in advanced.
Re: How to check input if it is number or not?
I just write this program for you just try to compile in your computer and let me know whether it work or not.
#include<stdio.h>
#include<ctype.h>
int is_number(char * pchar, int lnum)
{
int i, is_num=0;
for(i=0; i<lnum; i++)
{
if(!isalnum(*pchar)) break;
// printf("%c - ",*pchar);
if(!isdigit(*pchar))
{
is_num++;
break;
}
pchar++;
}
// printf("\nis_num = %i\n",is_num);
return is_num;
}
int main(void)
{
char num[50];
printf("\n number: ");
scanf("%s",num);
if(!is_number(num,50))
{
printf("number input correct\n");
}
else
{
printf("invalid input\n");
}
return 0;
}
I think this will help you.
Re: How to check input if it is number or not?
I think this is a simplest code in "c" to check input is number or not.
#include <stdio.h>
int main(void)
{
float num1;
printf("Please enter a number:");
while(! scanf("%f", &num1))
{
printf("\n\tInvalid entry, please enter correct entry: ");
fflush(stdin);
}
printf("The number you entered was %.2f\n", num1);
getChar();
}
Re: How to check input if it is number or not?
There is an option in "c" to check if the input is an integer or not through the return value of scanf. If the return value is not equal to 1 than the input is not an integer.I just write program for you, check whether it works or not.
int main(void)
{
int number, status;
int p = 1;
do
{
printf(" Enter your number:");
status = scanf("%d", &number);
while(status != 1)
{
printf("The input is not numeric. Try again:");
status = scanf("%d", &number);
}
for(p=1;p<= number; p++)
{
printf("*");
}
printf("\n");
}
while(number >= 1);
printf("End\n");