# Mini mind reader

Here is a code that guesses the number chosen by the user. I know that using goto is a bad practice, but it seems unavoidable here.

that's because using do while doesn't work, for example:

do{
scanf("%c",&variable);
}while(variable == 'a' || variable = 'b' || variable = 'c');


would accept all letters while I want it to accept only a,b and c, so I think using if/else and goto is better.

#include <stdio.h>
#include <time.h>

void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock());
}
int main()
{
int guess;
int tries=0;
char answer;
answer='y';
int min =0;
int max = 101;
int avg;
int a =0;
int i,j;

puts("pick a number between 1 and 100");
puts("if the number is higher than the guess press h");
puts("if it is less than the guess press l ");
puts("if my guess is correct press y");

for(i=0; (i< 8); i++)
{
sleep(600);
avg = (min + max)/2;
if(!avg)
break;

printf("is it %d\?\n", avg );
fff:
answer = getchar();

if(answer == 'y')
{
a++;
break;
}
else if(answer == 'h')
{
min = avg;
}
else if(answer == 'l')
{
max = avg;

}
else
goto fff;
}

int sol = rand() % 4 + 1;
if(a)
{

switch(sol)
{

case 2: puts("You are not good enough to beat me, human");
break;

case 3: puts("Stop wasting my time, your numbers are so easy to guess");
break;
case 4: puts("Next");
break;
//case 1:
default:

printf("That was easy your number is : %d ", avg);
break;

}

}
else
{
xa:
switch(sol)
{
case 2:
puts("Are you sure about this number");
break;

case 3: puts("I don't support imaginary numbers");
break;
case 4: puts("Stop playing with me");
break;

//case 1:
default:
puts("I think there is no such number");
}

}
sleep(2000);
getchar();

return 0;

}

-
If goto is inevitable, a label named fff: has to be ;) – Mat's Mug Mar 13 '14 at 16:15
Please don't edit your question in a way that will make answers look invalid. – Simon Forsberg Mar 13 '14 at 17:29

## 1 Answer

Bad things happen when you use use GOTO.....

The problem with your while loop is that you are using = instead of == .... you are assigning the values to the variable inside the loop, and it is successful, thus accepts all characters......

do{
scanf("%c",&variable);
}while(variable == 'a' || variable = 'b' || variable = 'c');


Fix it....

  do{
scanf("%c",&variable);
}while(variable == 'a' || variable == 'b' || variable == 'c');


EDIT:

Actually, the do-while loop may not be the best it needs to be bigger.... consider the following:

int ok = 1;

do
{
printf("is it %d\?\n", avg );
answer = getchar();
if(answer == 'y')
{
a++;
ok = 1;
break;
}
else if(answer == 'h')
{
ok = 1;
min = avg;
}
else if(answer == 'l')
{
ok = 1;
max = avg;
}
else
{
ok = 0;
printf("Illegal input %c\n", answer);
}
} while (!ok)

-
@nathan - edited answer with decent loop. – rolfl Mar 13 '14 at 16:29
Get back to your Java world! ;) – syb0rg Mar 13 '14 at 23:58