[英]break free from while loop when enter key entered in c
#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我做了一个这样的代码,我想在按下 Enter 键时摆脱 while 循环,所以我添加了代码 if
(anykey=='\\n')
但它不起作用我的代码有什么问题
scanf(" %c", &anykey);
consumes the newline from stdin
before actually reading any character, which is why anykey
never actually ends up being \\n
在实际读取任何字符之前使用
stdin
的换行符,这就是为什么anykey
实际上从未最终成为\\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.如果您必须将换行符作为中断条件(因为按回车键会停止程序),最好为此使用
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.