2012-10-12 22 views
1

我想讓我的程序只在用戶輸入Y或Y時運行,但它只運行一次,即使它不是Y或Y.輸入要麼是Y,Y,N或N做或同時?

printf("Welcome to the Jumble Puzzle Solver!\n\n"); 
printf("Would you like to enter a jumbled word?\n"); 
scanf("%s", &answer); 


    do{ 

    printf("What word would you like scored?\n"); 
    scanf("%s", &letters); 

    strcpy(changeletters, letters); 

    recursivepermute(letters, changeletters, checkword, k, dictionary ,max, min); 

    printf("Would you like to enter a jumbled word?\n"); 
    scanf("%s", &answer); 

    }while (answer == 'Y' || answer == 'y'); 
+2

什麼類型的答案?此外,家庭作業標籤已棄用。 – chris

+0

[頂部或底部的測試循環? (while vs. do while)](http://stackoverflow.com/questions/224059/test-loops-at-the-top-or-bottom-while-vs-do-while) – alk

回答

1

do { } while()導致身體總是被執行至少一次。如果你想在條件首先檢查,只需使用而:

// If answer is: 
// char answer; 

scanf("%c", &answer); 
while (answer == 'Y' || answer == 'y') 
{ 
    printf("What word would you like scored?\n"); 
    // ... 

    scanf("%c", &answer); 
} 

你還需要使用scanf("%c"如果answerchar%s將掃描一串字符(即:char[20]),並且需要使用類似strcmp或類似的方法進行不同的檢查。

+0

好的,但解釋使很有道理。我改變了它t%c,並做了這樣的while循環,但即使我輸入Y或Y它仍然結束程序。 – Ryan

+0

@Ryan在調試器中檢查你在'answer'中得到了什麼。是'是'還是'是'? 「答案」是如何申報的? –

+0

啊想出了我的問題。仍然有它聲明爲字符答案[2],而不是隻是字符答案。感謝您的幫助! – Ryan

0

如果你想讓用戶玩一次遊戲,然後被問及再玩的話,使用do-while循環更合適。但是如果你想讓用戶選擇不玩遊戲,那麼使用while循環

+0

謝謝你解釋了很多 – Ryan