2012-12-11 18 views
6

我正在學習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);,然後正常工作。
爲什麼會發生這種情況?任何想法?

+0

當你輸入'num'並按下ENTER時,所以ENTER的ascii碼存儲在scanf緩衝區中,並且每當你讀取下一個單個字符時,它都不會等待用戶輸入,並且將會存儲'ENTER'ascii碼在另一個變量中。 –

回答

1

在這種情況下使用getch()而不是scanf()。因爲scanf()期望'\ n',但是您只接受該scanf()處的一個字符。所以'\ n'給下一個scanf()造成混亂。

10

%c轉換會從輸入中讀取下一個單個字符,而不管它是什麼。在這種情況下,您以前使用%d來讀取一個數字。你必須按回車鍵才能讀取該號碼,但是你還沒有做任何事情來從輸入流中讀取新行。因此,當您執行%c轉換時,它會從輸入流中讀取新行(無需等待您實際輸入任何內容,因爲已有輸入等待讀取)。

當您使用%s時,它會跳過任何前導空格以獲取除空格之外的其他字符。它將新行視爲空白行,因此它隱含地跳過等待的新行。由於(大概)沒有別的東西在等待閱讀,所以它會繼續等待你輸入一些東西,正如你顯然希望的那樣。

如果要使用%c進行轉換,可以在格式字符串中使用空格,該格式字符串中的空格也會跳過數據流中的任何空格。

+0

謝謝你的信息 –

+0

@JessicaLingmn:當然可以。 –

0
#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"); 
    getchar(); 
    scanf("%c", &another); 
} 
} 
2

在輸入第一個scanf%d的編號後,ENTER鍵位於標準輸入流中。這個鍵被scanf%c行捕獲。使用scanf("%1s",char_array); another=char_array[0];

+1

-1用於推薦[未定義的行爲](http://c-faq.com/stdio/stdinflush.html)。 – Lundin

+0

我的不好......編輯答案。 – anishsane