Reputation: 37
I can't get my for loop switch to work. I want the program to repeat the question if the user type a letter other than 'y','Y','n','N'. Can someone help me fix please?
#include <stdio.h>
int main(void) {
int flag = 0;
char mstatus;
printf("Are you married?\n");
scanf(" %c", &mstatus);
for (; flag == 1;) {
printf("Are you married?\n");
scanf(" %c", &mstatus);
switch (mstatus) {
case 'y':
case 'Y':
printf("You have answer yes for married");
flag = 1;
break;
case 'n':
case 'N':
printf("You have answer no for married");
flag = 1;
break;
default:
printf("please re-enter a valid answer");
scanf(" %c", &mstatus);
}
}
return 0;
}
Upvotes: 1
Views: 230
Reputation: 32586
you have several problems in your code
The first couple
printf("Are you married?\n"); scanf(" %c", &mstatus);
is done for nothing because you do not use the read answer, remove these lines
In
for (; flag == 1;) {
you immediately exit the loop because you initialized flag to 0, and this is not consistent with how you change the value of flag, compare it with 0 rather than 1
In
default: printf("please re-enter a valid answer"); scanf(" %c", &mstatus);
the scanf must be removed because you do not use read answer
Out of that, because you want to do the loop at least one time to ask for the answer and manage it, it is very more readable to use a do ...while
Also add a final newline when you print something
Example :
#include <stdio.h>
int main(void) {
int flag = 0;
do {
char mstatus;
printf("Are you married?\n");
scanf(" %c", &mstatus);
switch (mstatus) {
case 'y':
case 'Y':
printf("You have answer yes for married\n");
flag = 1;
break;
case 'n':
case 'N':
printf("You have answer no for married\n");
flag = 1;
break;
default:
printf("please re-enter a valid answer\n");
}
} while (flag == 0);
return 0;
}
Compilation and executions :
pi@raspberrypi:/tmp $ gcc -Wall d.c
pi@raspberrypi:/tmp $ ./a.out
Are you married?
a
please re-enter a valid answer
Are you married?
y
You have answer yes for married
pi@raspberrypi:/tmp $ ./a.out
Are you married?
d
please re-enter a valid answer
Are you married?
N
You have answer no for married
pi@raspberrypi:/tmp $
Of course in your case there is nothing after the loop, so you can also simplify all removing flag and its management and replace the two first break by a return 0, of course in that case the loop can be for(;;) or while(1) etc
Probably please enter a valid answer is a better choice than please re-enter a valid answer because by definition the user never enter a valid answer so he cannot re-enter one
Upvotes: 1