Forum Discussion
Altera_Forum
Honored Contributor
12 years agoI myself find another way to circumvent this problem. That is to declare sex as a string, that is char sex[2], as shown below:
#include <stdio.h>
# include <string.h>
void main(void)
{
char sex;
char area;
do
{
printf("Please select your area (QLD, NSW, ACT, SA, WA, NT or TAS): ");
scanf("%s", area);
} while(strcmp(area,"QLD")!= 0 && strcmp(area,"NSW")!= 0 && strcmp(area,"ACT")!= 0 &&
strcmp(area,"SA")!= 0 && strcmp(area,"WA")!= 0 && strcmp(area,"NT")!= 0 && strcmp(area,"TAS")!= 0);
do
{
printf("Please enter your sex (M/F): ");
scanf("%s",sex);
}while(strcmp(sex,"M")!= 0 && strcmp(sex,"F")!= 0);
} In this way, a single ENTER character, even it is stored in sex, will not make strcmp TRUE and activate the do-while loop twice. And we don't need to clear stdin buffer. But this seems a waste. Every case for which we only need a character now needs to be replaced by a two-character string. Is there a better way?