Reputation: 17
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define BAR 1
#define BELL 2
#define LEMON 3
#define CHERRY 4
#define RMAX 4
void main()
{
int slot1, slot2, slot3;
char anykey;
while (1)
{
printf("Type any key to start the slot machine \n");
scanf(" %c", &anykey);
if (anykey == '\n')
{
break;
}
srand(time(NULL));
slot1 = 1 + (int)rand() % RMAX;
slot2 = 1 + (int)rand() % RMAX;
slot3 = 1 + (int)rand() % RMAX;
if (slot1 == slot2 && slot2 == slot3 && slot1 == 1)
printf("Congradulations On A JACKPOT\n");
else if (slot1 == 1 || slot2 == 1 || slot3 == 1)
printf("ONE dime \n");
else if (slot2 == slot1 && slot2 == slot3)
printf("One Nickel \n");
else printf("Sotrry better luck next time\n");
}
}
I made a code like this and I want to break free from while loop when
enter key is pressed
so I add the code if (anykey=='\n')
but it doesn't work
what is wrong with my code
Upvotes: 1
Views: 61
Reputation: 5615
scanf(" %c", &anykey);
consumes the newline from stdin
before actually reading any character, which is why anykey
never actually ends up being \n
If you must have the newline as a break condition (as in hitting enter will stop the program), you're better off using getchar
for this, you can use scanf("%c", ...)
but that's a bit overkill.
printf("Type any key to start the slot machine \n");
int ch = getchar();
/* Should check for `EOF` too */
if (ch == '\n' || ch == EOF)
{
break;
}
anykey = (char) ch;
Upvotes: 2