2016-09-17 73 views
1

我是C新手,並且很喜歡學習它,但是我遇到了一個與我的程序有關的問題,我很難嘗試弄清楚。在下面的程序中,如果用戶輸入「1」,則將提示他們輸入「密鑰」,「年齡」,「名字」和「姓氏」。但是,當用戶輸入「1」時,程序不會等待用戶輸入「Key」值,而是直接打印到「Age」。C程序不會等待用戶輸入值

進入「1」後的輸出:

輸入以下信息:按鍵 :年齡:

程序要求之前不會等待用戶在一個鍵值進入,用戶輸入年齡值。程序編譯時不會發生錯誤或警告。

任何和所有的幫助,非常感謝。

typedef struct userInputsContainer { 
    char inputOption[2]; 
    char inputKey[2]; 
    char inputAge[3]; 
    char inputFName[10]; 
    char inputLName[10]; 
}userInputsContainer; 

int main() 
{ 
    struct userInputsContainer* container = (struct  userInputsContainer*)malloc(sizeof(userInputsContainer)); 

    printf("List of options..\n"); 
    printf("1.Create Entry\n2.Search Entries\n"); 
    fgets(container->inputOption, sizeof(container->inputOption), stdin); 

    if(container->inputOption[0] == '1') 
    { 
     printf("\nEnter the following information.. \n"); 

     printf("Key: "); 
     fgets(container->inputKey, sizeof(container->inputKey), stdin); 
     printf("Age: "); 
     fgets(container->inputAge, sizeof(container->inputAge), stdin); 
     printf("First Name: "); 
     fgets(container->inputFName, sizeof(container->inputFName), stdin); 
     printf("Last Name: "); 
     fgets(container->inputLName, sizeof(container->inputLName), stdin); 
    } 
} 
+1

@ user3121023沒有要求存儲一個字符。那麼空行呢? – Olaf

回答

0

對於最初的輸入,當你讀入container->inputOption,數組inputOption有足夠的空間,以適應一個字符和字符串結束。問題是fgets通常也想在輸入後讀取換行符,並將其添加到緩衝區。如果緩衝區中沒有空間(這裏是這種情況),則fgets將不會讀取換行符並將其保留在輸入緩衝區中。所以下一次撥打電話fgets會將此換行看作是第一個字符,並且認爲它讀取了整行內容,並且沒有再讀取任何內容。

這個問題基本上有兩種解決方案:第一種是將container->inputOption數組的大小從兩個增加到三個字符,所以它將適合新行。

第二種解決方案是在第一個調用fgets之後有一個循環,它讀取並放棄字符,直到它讀取換行符。

+0

非常感謝你的解釋,我絕對學到了一些新東西!這解決了我的問題! –