Categories

วันจันทร์ที่ 13 กรกฎาคม พ.ศ. 2552

Check input is number or not

#include 
// Need ctype.h for isdigit and isalnum functions.
#include 

int main(void)
{
 char var[10];    // This is the variable to store input.
 int i = 0;
 int varisnum = 0;    // Is var all numbers?  1 for yes, 0 for no.
 
 scanf("%s", var);

 while (isalnum(var[i]) != 0) {    // Loop until it a character is not alpha-numeric.
  if (isdigit(var[i]) != 0) {    // Is var[i] a numeric digit?
   varisnum = 1;
  } else {
   varisnum = 0;
   break;    // If we encounter a non-numeric character, there is no need to keep looping, so just break out.
  }
  i++;    // Move counter to the next element.
 }
 
 if (varisnum == 0)
  printf("Input was not all numbers.\n");
 else
  printf("Input was all numbers.\n");
 
 return 0;
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น

Search