I want to create a program in C to check for @ and . if typed in by user -
checking email address if user typed in @
, .
symbols. how can fix code?
void emailaddress(){ char emailadd[50]; int emailaddl, i; printf("please enter email address\n"); scanf("%s", emailadd); emailaddl=strlen(emailadd); for(i=0; i<=emailaddl; i++){ if(emailadd[i]!='@'){ printf("the entered email address incorrect. please re-enter email address , must contain '@' specifier\n"); emailadd=(int*)calloc(emailadd, sizeof(char)); scanf("%s", emailadd); } if(emailadd[i]!='.'){ printf("the entered email address incorrect. please re-enter email address , must contain '.' specifier\n"); emailadd=(int*)calloc(emailadd, sizeof(char)); scanf("%s", emailadd); } else continue; } }
the major problem code facing not c logical structure of function. if emailadd
contains character different @
and/or different .
ask new email address. that's not want.
let's structure problem. here want do:
- get user input
- check if input contains
@
- if not, ask new input
- check if input contains
.
- if not, aks new input
you don't want once, long user input correct. more precise want .
after @
(otherwise email address stack.overflow@so
valid.
consider approach implements behaviour defined above:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char emailadd[50]; size_t emailaddl; /* use size_t instead of int */ /* email address first time */ printf("please enter email address\n"); scanf("%s", emailadd); emailaddl=strlen(emailadd); /* loop while address has wrong format */ while(1){ /* create flags: 0 character missing, 1 character found */ int at_flag=0; int dot_flag=0; emailaddl=strlen(emailadd); /* loop through char array. have loop 0 array lenght -1*/ for(int i=0; i<emailaddl; i++){ /* can declare variables in loops */ /* if @ has been found, set flag */ if(emailadd[i] == '@'){ at_flag=1; } /* if . has been found , @ has been found earlier, set flag */ if(at_flag && emailadd[i] == '.'){ dot_flag=1; } /* if both flags have been set, can stop searching */ if(at_flag && dot_flag){ break; } } /* if no @ has been found, ask */ if(!at_flag){ printf("the entered email address incorrect. please re-enter email address , must contain '@' specifier\n"); scanf("%s", emailadd); /* if @ has been found, no ., ask */ } else if(!dot_flag){ printf("the entered email address incorrect. please re-enter email address , must contain '.' specifier, after '@' specifier\n"); scanf("%s", emailadd); /* otherwise leave loop */ } else{ printf("everything fine!\n"); break; } } }
let's try scenarios:
$ please enter email address $ stack.overflow $ entered email address incorrect. please re-enter email address , must contain '@' specifier $ stack.overflow@so $ entered email address incorrect. please re-enter email address , must contain '.' specifier, after '@' specifier $ stack.overflow@so.com $ fine!
Comments
Post a Comment