How to prevent non numeric or non character input or symbols and getting desired output in C -
here's source code modified youtube tutorial. purpose of program is:
it ask age. if put 18 or more ask gender print can enter dude or m'lady(depends on gender). if put age less 18 prints "nothing see here!"
i want make sure if input isn't ask(only number or character) shows "invalid input". in program, first part program ask age, when input age either alphabet or symbol shows invalid input. whenever combine alphabet number 18a or 18/ shows:
"please enter gender.(m/f)" "invalid input."
also, if input 18 or more , go part program ask gender(m/f) shows invalid input if put number or symbol.. when combine m1 or m/ shows:
"you may enter website dude."
can me how can remove problem?
#include <stdio.h> #include <conio.h> int main(void) { char gender; int age=0; printf("please enter age. \n"); if(scanf(" %d",&age)!=1) { printf("invalid input. \n"); return 0; } if(age>=18) { printf("please enter gender.(m/f) \n"); if(scanf(" %s", &gender) !=1) { printf("invalid input.\n"); return 0; } else if(gender== 'm') { printf("you may enter website dude.\n"); } else if(gender== 'f') { printf("you may enter website m'lady.\n"); } else { printf("invalid input. \n"); return 0; } } else if(age<18) { printf("nothing see here! \n\n"); return 0; } return 0; }
if want avoid kind of behavior should read entire line each user option , validate completely.
to read entire line can use scanf(" %[^\n]",str)(*) instead of using %d or %s. can validate user input check if wanted.
extra: validate age can use: strtol explained here, , validate gender think simple string comparison trick.
(*) there several options available read entire line in c (fgets example), , there reasons not use scanf(" %[^\n]",str) (possible buffer overflows) tried show solution function using, nice discussion topic take @ this post.
Comments
Post a Comment