I wrote a program: #include /**/ int main(){ int i = 1; while(i !=0){ printf(\"H
ID: 3783214 • Letter: I
Question
I wrote a program:
#include
/**/
int main(){
int i = 1;
while(i !=0){
printf("Hit Enter to quit, or Enter an indenfier: ");
char c;
int count = 0;
int status = 1;
char a;
if ((c=getchar())==' '){
printf("Thanks for your input. ");
break;
}else{
while( (c = getchar()) != ' '){
count++;
// if this is the first character of identifire, then it should be either '_' or alphabets
if(count == 1){
if((c != '_') && !(c >='A' && c<='Z') && !(c >= 'a' && c <='z')){
status = 0;
}
}
else if((c != '_') && !(c >='A' && c<='Z') && !(c >= 'a' && c <='z') && !(c >= '0' && c <='9')){
status = 0;
}
}
}
if(count == 0 || status == 0)
printf("Invalid ");
else
printf("Valid ");
}
return 0;
}
This giving me the output below:
It is wrong because it eaxm the valid and invalid from second like 1 in the a1 just skip a in the a1.
But If I deleate the following part:
if ((c=getchar())==' '){
printf("Thanks for your input. ");
break;
}else{
Then the results are correct, however there is no stop of calling for an input.
How can I fix this to have the program end when type in nothing or type in a specific key?
And the same time always test the validility from the beginning.
CAUsers 54985 DocumentsC-Free Projects Studymingw5MSt Hit Enter to quit or Enter an indenfier Invalid Hit Enter to quit or Enter an indenfier: Invalid Hit Enter to quit or Enter an indenfier: Invalid Hit Enter to quit or Enter an indenfier: Invalid Hit Enter to quit or Enter an indenfier: as Walid Hit Enter to quit or Enter an indenfier: al Invalid Hit Enter to quit or Enter an indenfier: a2 Invalid Hit Enter to quit or Enter an indenfier: Thanks for your input. Press any key to continueExplanation / Answer
This is simple! just use do while loop insted of while loop as given below (I just changed the loop only)
CODE
#include <stdio.h>
/**/
int main(){
int i = 1;
while(i !=0){
printf("Hit Enter to quit, or Enter an indenfier: ");
char c;
int count = 0;
int status = 1;
char a;
if ((c=getchar())==' '){
printf("Thanks for your input. ");
break;
}else{
do{
count++;
// if this is the first character of identifire, then it should be either '_' or alphabets
if(count == 1){
if((c != '_') && !(c >='A' && c<='Z') && !(c >= 'a' && c <='z')){
status = 0;
}
}
else if((c != '_') && !(c >='A' && c<='Z') && !(c >= 'a' && c <='z') && !(c >= '0' && c <='9')){
status = 0;
}
}while( (c = getchar()) != ' ');
}
if(count == 0 || status == 0)
printf("Invalid ");
else
printf("Valid ");
}
return 0;
}
OUTPUT
sh-4.2$ main
Hit Enter to quit, or Enter an indenfier:
a
Valid
Hit Enter to quit, or Enter an indenfier:
a
Valid
Hit Enter to quit, or Enter an indenfier:
sd
Valid
Hit Enter to quit, or Enter an indenfier:
a1
Valid
Hit Enter to quit, or Enter an indenfier:
a2
Valid
Hit Enter to quit, or Enter an indenfier:
23d
Invalid
Hit Enter to quit, or Enter an indenfier:
Thanks for your input.