我知道这样的问题一直被问到,而且我已经阅读了几个,但是,我从来没有scanf()
像其他所有代码一样在我的代码中使用过,所以我找不到类似的问题。我不知道为什么在第二次、第三次、第四次等迭代中,while 循环跳过了我的第一个fgets()
.
代码:
int main()
{
char word[40];
char answer[2];
while(true) {
printf("Please enter word: ");
fgets(word, sizeof(word), stdin);
printf("Your word is: %s\n", word);
printf("Would you like to go again?");
fgets(answer, sizeof(answer), stdin);
printf("%d\n", strcmp(answer, "F"));
if (strcmp(answer, "F") == 0) {
printf("breaking");
break;
} else {
printf("continuing");
continue;
}
}
}
输出:
Please enter word: Hey
Your word is: Hey
Would you like to go again?Y
Please enter word: Your word is:
Would you like to go again?Y
Please enter word: Your word is:
Would you like to go again?Y
...ETC。
我认为这与清除输入缓冲区有关,我尝试了几件事,但没有任何效果。第二天乱搞C,所以我不太了解。(Python 更简单,哈哈)