如何解决在C中输入Enter键时,从while循环中摆脱出来
#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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。