2017-03-04 67 views
0

我試圖從用戶那裏獲取輸入,並且fgets正在跳過第一個輸入。我知道原因是與fgets是讀從以前的聲明「\ n」或至少我認爲是這樣的原因,但我似乎無法修復它C fgets跳過用戶輸入,即使在刷新緩衝區時

注意,這是一個更大的項目的一部分

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAX 1000 

int main(void) { 

    char content[MAX]; 
    char content2[MAX]; 
    char content3[MAX]; 
    char content4[MAX]; 
    char content5[MAX]; 
    char input[4]; 
    char input2[4]; 

    printf("Do you want to continue yes/no?\n"); 
    fgets(input, 4, stdin); 

    if (strncmp (input, "no", 2) == 0) { 
    break; 
    } 
    else if (strncmp (input, "yes", 3) == 0) { 
    fflush(stdin); 

    printf("Country:\n"); 
    fgets(content, MAX, stdin); 

    printf("Province/state: \n"); 
    fgets(content2 ,MAX, stdin); 

    printf("Postal/zip code:\n"); 
    fgets(content3 ,MAX, stdin); 

    printf("Company:\n"); 
    fgets(content4 ,MAX, stdin); 

    printf("Email:\n"); 
    fgets(content5 ,MAX, stdin); 
    } 
+1

這正是發生的情況。最簡單的解決方法是增加'input'的大小。你希望在*是/否結束時*調用'fgets'來獲取換行符 – StoryTeller

回答

3

"yes"加終止空字符消耗4字節,所以'\n'保留在緩衝區中。將更多緩衝區分配到input,並將其新長度傳遞到fgets()以讀取yes而不在流中留下換行符。

另請注意,fflush(stdin);調用未定義的行爲,所以你不應該使用它。

+0

非常感謝你的支持!順便說一句,我知道這與問題無關,但是你有什麼我應該使用而不是fflush的個人建議? – kirkosaur

-2

您是否嘗試在fflush中添加stdin?你應該有這樣的東西:

fflush(stdin);

+1

不,你不應該。在輸入流上調用'fflush'具有未定義的行爲。這是可怕的建議。 – StoryTeller

0
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define MAX 1000 

int main(void) { 

    char content[MAX]; 
    char content2[MAX]; 
    char content3[MAX]; 
    char content4[MAX]; 
    char content5[MAX]; 
    char input[4]; 
    char input2[4]; 

    printf("Do you want to continue yes/no?\n"); 
    fgets(input, 4, stdin); 

    if (strncmp (input, "no", 2) == 0) { 
    exit(0); 
    } 
    else if (strncmp (input, "yes", 3) == 0) { 
    fflush(stdin);//this is not portable 
    while(getchar()!='\n');//this thing works 
    printf("Country:\n"); 
    fgets(content, MAX, stdin); 

    printf("Province/state: \n"); 
    fgets(content2 ,MAX, stdin); 

    printf("Postal/zip code:\n"); 
    fgets(content3 ,MAX, stdin); 

    printf("Company:\n"); 
    fgets(content4 ,MAX, stdin); 

    printf("Email:\n"); 
    fgets(content5 ,MAX, stdin); 
    } 
} 

fflush()不適用於大多數情況。請使用以下代碼代替

while(getchar()!='\n');