问题描述
#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");
}
}
我做了这样的代码,我想从while循环中摆脱出来
按下输入键
所以我添加了代码(anykey=='\n')
,但它不起作用
我的代码有什么问题
解决方法
scanf(" %c",&anykey);
在实际读取任何字符之前会消耗stdin
中的换行符,这就是anykey
从未真正以\n
结束的原因
如果必须将换行符作为中断条件(如按回车键将停止程序),则最好使用getchar
,可以使用scanf("%c",...)
,但这有点过度杀伤力。
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;