為什么我的do/while回圈在檢查條件之前會重復 2 次?
int main() {
char quit;
quit = getchar();
do {
printf("Next state: ");
clock_t start = clock();
count_values(a, b);
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
print_state(b);
printf("\nTime: %f\n", seconds);
swap(a, b);
printf("Press enter to print next generation. To quit, enter 'q'.");
quit = getchar();
} while(quit != 'q');
return 0;
}
只有回圈重復了2次后,才getchar()等待輸入,為什么?如何解決?
uj5u.com熱心網友回復:
您可能正在手動輸入,因此當您按下該Enter鍵時,會留下一個換行符,然后第二次getchar()呼叫會使用該字符。
要繞過這一點,您可以使用fgets().
char quit[100];
fgets(quit, sizeof(quit), stdin);
do {
printf("Next state: ");
clock_t start = clock();
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
printf("\nTime: %f\n", seconds);
printf("Press enter to print next generation. To quit, enter 'q'.");
fgets(quit, sizeof(quit), stdin);
} while(quit[0] != 'q');
雖然上面的代碼應該做的作業,可以很容易地欺騙程式,通過鍵入任何打頭q。
解決方案是使用strcmp()檢查字串是否僅包含"q".
請注意,fgets()還將換行符存盤在緩沖區中,以繞過您需要將其替換為NULL位元組。
char quit[100];
do {
printf("Next state: ");
clock_t start = clock();
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
printf("\nTime: %f\n", seconds);
printf("Press enter to print next generation. To quit, enter 'q'.");
fgets(quit, sizeof(quit), stdin);
quit[strcspn(quit, "\n")] = '\0'; /* get rid of \n */
} while(strcmp(quit, "q") != 0);
uj5u.com熱心網友回復:
它并沒有檢查條件之前重復兩次。您可以通過稍微修改您的代碼來檢查它,這也使它成為一個最小的可重現示例:
#include <stdio.h>
int test(char c) {
printf("Testing input: %d\n", c);
return c != 'q';
}
int main() {
char quit;
quit = getchar();
do {
printf("Press enter to print next generation. To quit, enter 'q'.\n");
quit = getchar();
} while(test(quit));
return 0;
}
您可以看到在第一個回圈之后輸入已經被測驗。不是'q',如果你輸入q然后[enter]。在q將被消耗quit = getchar(); 之前的回圈。然后將在條件中檢查換行符(十進制 10),而不是q.
所以你的假設是錯誤的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/382575.html
