Advertisement
MAGCARI

Check if input is integer or not

May 2nd, 2024
569
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.68 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<stdlib.h>
  4. int main() {
  5.     char inp[100];
  6.     // receive input as string
  7.     scanf(" %s", inp);
  8.    
  9.     // use strlen function to get the length of the string
  10.     int len = strlen(inp);
  11.  
  12.     // check if the input is valid by looping through the string from 0 to len-1
  13.     for(int i=0;i<len;i++) {
  14.         // if the character ASCII value is not between 0 and 9, then it is not a digit
  15.         if(inp[i] < '0' || inp[i] > '9') {
  16.             printf("Invalid input\n");
  17.             return 0;
  18.         }
  19.     }
  20.  
  21.     // if the loop completes without returning, then the input is valid
  22.     // convert the string to integer using atoi function
  23.     int num = atoi(inp);
  24.  
  25.     // print the integer
  26.     printf("The number is %d\n", num);
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement