but at the end it loops like 2 or 4 times, displaying all the printf messages,
There are several ways to avoid that, one will be to add after scanf this:
while((check=getchar()) != EOF && check != '\n');
Any way a minimal code will look like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char a;
int check,ok=0;
do {
printf("Give an A: ");
if ((scanf("%c",&a)) == 1){
while((check=getchar()) != EOF && check != '\n');
if ((a == 'a') || (a == 'A')){
printf("True\n");
ok=0;
} else {
printf("False\n");
ok = 1;
}
}else{
printf("Error");
exit(1);
}
}while (ok == 1);
return 0;
}
But the way how you approach this , a fix will probably look like this:
#include <stdio.h>
#include <stdlib.h>
int main(void){
char userresponse;
int check,ok=0;
char x;
do {
printf("are you human: ");
if ((scanf("%c",&userresponse)) == 1){
while((check=getchar()) != EOF && check != '\n');
if ((userresponse == 'y') || (userresponse == 'Y')){
printf("welcome\n");
break;
} else {
printf("please leave\n\n");
printf("type z to repeat");
if(scanf("%c",&x) == 1){
while((check=getchar()) != EOF && check != '\n');
if(x=='z' || x == 'Z'){
ok = 1;
}else{
printf("\n");
printf("Wrong Input\nGoodBye\n");
break;
}
}else{
break;
}
}
}else{
printf("Error");
exit(1);
}
}while (ok == 1);
return 0;
}
What I'm trying here to explain is that there is no reason to stick with a condition in that while like x=='z', just use another variable like in the above examples.
Just give it a try.
EDIT:
If you need to start form your code, than here is a quick fix:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char userresponse;
char x;
do {
printf("are you human");
if(scanf(" %c", &userresponse) ==1){
if (userresponse == 'y' || userresponse == 'Y') {
printf("welcome\n");
}
printf("type z to repeat\n");
if(scanf(" %c", &x) != 1){
printf("Error");
exit(1);
}
}else{
printf("Error");
exit(1);
}
} while (x == 'z' || x == 'Z');
return 0;
}
As you probably see, I try to avoid your problems.
1) I check scanf for errors
2) i put a space in front of %c to avoid '\n'.
3) I check for y and Y and for z and Z.
{}button above the edit box to indent it by four spaces, which makes it appear as code. Your code will be a lot easier to understand if it is indented. As originally presented, it is close to inscrutable. Don't forget to include a newline at the end of outputs that are not prompts (and do include a space at the end of outputs that are prompts).yandenteras input.. it will go 2 characters to your program. You are getting the firsty.. but there's also the\nnext. You can fix by forcing it to ignore new line withscanf("%c%*c",&x)elses in your program. There are 2 identicalifs which produce seemingly opposite results." %c"to read characters; it will ignore white space, including newlines, and processes the next character that is not white space.