Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR C

how to prevent user from entering char when needing int in c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i=0, isFloat=0, isChar=0;
    int intNum=0;
    float floatNum=0;
    char str[100];
    printf("Enter a number:");
    scanf("%s",str); // no &
    for(i=0; i<strlen(str); ++i)
    {
        // if not 0-9
        if(!((str[i]>='0')&&(str[i]<='9')))
        {
            if(str[i]=='.')
            {
                isFloat ++;
            }
            else{
                isChar ++;
            }
        }
    }
     if(isChar || isFloat > 1)
     {
         printf("This is not a number.");
     }
     else if(isFloat == 1)
     {
         printf("This is a float.");
         floatNum=atof(str);
         printf("input as float %.2f
",floatNum);
     }
     else {
         printf("This is a valid int.
");
         intNum=atoi(str);
         printf("input as int %d
",intNum);
     }
    return 0;
}
 
PREVIOUS NEXT
Tagged: #prevent #user #entering #char #needing #int
ADD COMMENT
Topic
Name
1+6 =