2014-08-27 38 views
1

我是新來的c和編寫鏈接列表中的c程序。它是一個簡單的程序。
我正在使用它來輸入數字列表,直到用戶想要的。do-while不按預期工作

的代碼爲:

do { 
    system("clear"); 
    printf ("\nEnter a no to add to list : "); 
    scanf ("%d",&num); 
    append (&p,num); 
    display (p); 
    printf ("\n\nWhant to add more...(Y/N) : "); 
    choice = getchar(); 
} while (choice == 'y' || choice == 'Y'); 

當用戶輸入的選擇,程序退出...

我使用Linux上[求助] GCC編譯器來編譯並運行它。

+1

'if(DidYouDownVote())cout <<「提供一個原因。」 << endl;' – 2014-08-27 17:21:56

回答

4

scanf讀取數並停止stdin閱讀,但是當你輸入一個號碼,你發送的數量加上\n字符。這是getchar()讀取的內容。它不是yY,所以循環結束。

更改與這一個你getchar()行:

scanf(" %c", &choice); 

...,它應該工作。

+0

謝謝......它爲我工作。 – 2014-12-13 15:55:06

1

推測:getchar();

choice = getchar();

要消耗的是留在stdinscanf()\n字符。然後

代碼結果:

do { 
    system("clear"); 
    printf ("\nEnter a no to add to list : "); 
    scanf ("%d",&num); 
    append (&p,num); 
    display (p); 
    printf ("\n\nWhant to add more...(Y/N) : "); 
    getchar(); //needed to consume the \n character 
    choice = getchar(); 
    }while (choice == 'y' || choice == 'Y'); 
1

getchar()從標準輸入(stdin

當您按下scanf()語句後輸入,一個\n性格得到了積累在輸入緩衝區返回下一個字符。因此choice的值自動設置爲\n,並且循環條件變爲false。

您可以使用scanf()而不是getchar()stdin中讀取格式化的數據,最終保存值爲choice

do { 
    system("clear"); 
    printf ("\nEnter a no to add to list : "); 
    scanf ("%d",&num); 
    append (&p,num); 
    display (p); 
    printf ("\n\nWhant to add more...(Y/N) : "); 
    scanf(" %c", &choice); 
} while (choice == 'y' || choice == 'Y'); 
+0

你的代碼不起作用:'scanf(「%c」)'確實收到了'\ n'。在'%c'之前需要額外的空間來擺脫所有空格,製表符和換行符 – 2014-08-27 19:45:53

+0

感謝您指點我:)修正了答案。 – 2014-08-27 19:55:54