我正在完成一項任務,完成後有1個錯誤和1個錯誤修復程序,因此我沒有完全理解。目前,只要用戶做了什麼要求,一切正常。但我知道這並不經常發生,所以我很想知道如何阻止這些問題。 很想任何意見 - 我是一個完整的初學者與C在for循環中的C - scanf()正在導致printf()運行多次
我發現很多不同點建議在這裏:C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
我添加了一個空間,我的scanf(),它解決了一些蟲子的語句 - 和我知道\ n被添加到輸入的字符串/字符的末尾,我只是不知道如何檢查它/處理它,並且我嘗試使用getchar()代替scanf(),但我仍然得到雙打印/循環問題。
錯誤版本
當用戶通過遊戲循環運行時,如果它們進入多於1個字符(例如:「OO」,當與scanf的提示()來輸入「Y」或「N」)我的printf語句運行1X每個字符的輸入,並連接到對方:
例子是:
歡迎兩扇門。
你想玩嗎? (年/月):歡迎來到兩扇門。
你想玩嗎? (y/n):
如果用戶輸入'y'來玩遊戲,但在第二部分輸入的字符不是1,2或3,那麼這個問題也會出現。
我該如何限制他們回覆的長度?或者是在輸入if語句之前監控比賽時間和選擇變量的最佳方式?也許檢查,看看他們是否超過1個字符,如果是,只採取第一個字符?
第二個問題 - 我不明白的錯誤修復 在scanf()函數中,我碰到了一個和我上面描述的類似的問題,但是當用戶輸入任何字符時發生了這種情況。我找到的解決方案是在字符前加一個空格 - >
scanf(" %c", &play);
VS
scanf("%c", &play);
是這個問題只有一個問題,使用循環什麼時候?因爲在循環代碼之前我從未發現這些錯誤。
用'while(getchar()!='\ n')更新代碼;''從Sourav戈什
#include <stdio.h>
int main(void) {
char play;
int choice;
char answer[] = "No matter which one you choose the guards both tell you which door leads to death, and therefore you can pick the other door.\n";
int gameLoop = 1;
int timesPlayed = 0;
while (gameLoop == 1){
if (timesPlayed == 0) {
printf("Welcome to Two doors.\n");
printf("Would you like to play? (y/n):");
} else {
printf("Would you like to play again? (y/n):");
}
scanf(" %c", &play);
while (getchar() != '\n');
if (play == 'y') {
// == instead of =
printf("\nYou are a prisoner in a room with 2 doors and 2 guards.\n");
printf("One of the doors will guide you to freedom and behind the other is a hangman --you don't know which is which.\n");
printf("One of the guards always tells the truth and the other always lies. You don't know which one is the truth-teller or the liar either.\n");
printf("You have to choose and open one of these doors, but you can only ask a single question to one of the guards.\n");
printf("What do you ask so you can pick the door to freedom?\n\n");
printf("\t1.Ask the truth-guard to point to the door of doom.\n");
printf("\t2.Ask the liar-guard to point to the door of doom.\n");
printf("\t3.Doesn't matter which one you pick.\n");
scanf(" %d", &choice);
while (getchar() != '\n');
switch (choice) {
case 1:
printf("%s", answer);
timesPlayed++;
break;
case 2:
printf("%s", answer);
timesPlayed++;
break;
case 3:
printf("%s", answer);
timesPlayed++;
break;
default:
printf("The Troll Smasher comes out from the shadows and squeezes the stupid out of you until you pop. GAME OVER!\n");
break;
}
} else if(play == 'n') {
printf("Sorry to hear that, we at Two Doors hope you have a super duper day!\n");
gameLoop = 0;
break;
} else {
printf("That is not a valid input, please try again by entering either 'y' to start the game or 'n' to quit the game.\n");
}
}
return 0;
}
我更新了我的文章中的代碼以使用您的建議。我是否正確使用它?我測試了所有的錯誤,他們似乎都解決了。這條線是否實現了多個目標?防爆。如果播放持有'\ n'值,則代碼無法執行;如果該值爲true,則清空輸入緩衝區?因爲它還修復了多個條目ooo(當有除\ n以外的其他字符\ n –