我正在學習C編程。我寫了一個奇怪的循環,但不起作用,而我在scanf()
中使用%c
。
下面是代碼:奇數循環無法使用%c
#include<stdio.h>
void main()
{
char another='y';
int num;
while (another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
scanf("%c", &another);
}
}
但如果我在這段代碼中使用%s
,例如scanf("%s", &another);
,然後正常工作。
爲什麼會發生這種情況?任何想法?
當你輸入'num'並按下ENTER時,所以ENTER的ascii碼存儲在scanf緩衝區中,並且每當你讀取下一個單個字符時,它都不會等待用戶輸入,並且將會存儲'ENTER'ascii碼在另一個變量中。 –