2013-08-21 20 views
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 
> 

回答

0

嘿嘗試使用下面的代碼,它必須工作。

scanf(" %c",&userChar); 
+0

像按鈕一樣工作!非常感謝! –

+0

現在,我們來完成您的任務,找出造成這一變化的原因 –

0

如果您在控制檯輸入

l<RETURN> 

然後有在輸入緩衝區中兩人的「L」和 一個換行符。 第一個scanf()讀取「l」,第二個scanf()讀取換行符。雖然這可以通過修改掃描格式來解決,但是從用戶輸入讀取整行的 的更好的解決方案是使用fgets(),例如,使用。

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

並注意邏輯 「或」 操作符是||,不|

相關問題