0
int main(int argc, const char * argv[])
{

@autoreleasepool {

    int userInput= 6 ;
    char userChar='\0';

    //creating new instances
    Dice *a = [[Dice alloc] init];
    //creating new objects
    Die *d1 = [[Die alloc] initWithSides:&userInput];
    Die *d2 = [[Die alloc] initWithSides:&userInput];
    //adding dices
    [a addDice:d1];
    [a addDice:d2];

    while(1)
    {
        printf("Press R to roll dices and Q to exit \n> ");
        scanf("%c",&userChar);

        if (userChar == 'r' | userChar =='R')
        {

            for (int i=0; i<10; i++)
            {
                [a rollDice];
                printf("Dice 1 =%d\n",d1.returns);
                printf("Dice 2 =%d\n",d2.returns);
                printf("The total values of both dice is %d\n",a.totalValue);
                printf("Does the dices have same value? Y(1) N(0) => %d\n\n",a.allSame);
            }
        }
        else if (userChar == 'q' | userChar == 'Q')
        {
            return 0;
        }

        else
        {
            printf("Enter a valid command!\n");
        }

    }

}
}

我试图创建一个重复的循环,当按下 r 时,当用户想要退出程序时做掷骰子和 q。否则,请不断重复,直到输入正确的输入。但我不明白为什么如果我输入一个输入,它会重复其他阶段?像这样,

Press R to roll dices and Q to exit 
>l
Enter a valid command!
Press R to roll dices and Q to exit 
>Enter a valid command!  //Why does it repeats itself here??
Press R to roll dices and Q to exit 
>
4

2 回答 2

0

嘿尝试使用下面的代码它必须工作。

scanf(" %c",&userChar);
于 2013-08-21T11:59:02.430 回答
0

如果你输入

 l<RETURN>

在您的控制台中,输入缓冲区中有两个字符:“l”和换行符。第一个scanf()读取“l”,第二个scanf()读取换行符。

虽然这可以通过修改扫描格式来解决,但是从用户输入中读取整行的更好的解决方案是使用fgets(),例如

char buf[100];
while (fgets(buf, sizeof(buf), stdin) != NULL) {
    userChar = buf[0];
    // ...
}

请注意,逻辑“或”运算符是||,不是|

于 2013-08-21T11:59:18.993 回答