2012-12-20 28 views
-1
時跳過

可能重複:這
scanf: 「%[^\n]」 skips the 2nd input but 「 %[^\n]」 does not. why?的scanf()正在試圖讀取包括空格

基本上我有一個客戶結構,其中我進入客戶的詳細信息,一是地址。當然地址是一個句子,因爲這是一個沒有圖形的基本文本程序。

我試圖使用scanf("%[^\n]",&VARIABLE)方法,因爲這在以前的程序中起作用。 但是在這裏,輸入被跳過。我在嘗試輸入緩衝區之前先刷新緩衝區,但沒有任何區別。我也嘗試創建另一個字符串,並將我的輸入傳遞給它,然後將數據複製到我的結構中,但這也不起作用。

這裏是我的代碼 - 問題是在第4 scanf("%[^\n]",&myCust.address)存在的:(注:這是一項正在進行的工作,所以你可能會看到,現在一些額外的打印和東西)

void addNewCustomer() 
{ 
    struct customer myCust; 
    printf("\n\nNEW CUSTOMER ADDITION\n"); 
    printf("\nEnter customer id : "); 
    scanf("%s",&myCust.idNumber); 
    printf("\nEnter customer name : "); 
    scanf("%s",&myCust.name); 
    printf("\nEnter customer surname : "); 
    scanf("%s",&myCust.surname); 
    fflush(stdin); 
    printf("\nEnter customer address : "); 
    scanf("%[^\n]",&myCust.address); 
    printf("\nEnter customer telephone : "); 
    scanf("%s",&myCust.telephone); 
    printf("\nEnter customer mobile : "); 
    scanf("%s",&myCust.mobile); 
    printf("\nEnter customer e-mail : "); 
    scanf("%s",&myCust.email); 

    FILE *fp; 

    fp = fopen("/Users/alexeidebono/Dropbox/Customer_Application/customers.dat","a"); 
    if (fp == NULL) { 
     printf("The File Could Not Be Opened.\n"); 
     exit(0); 
    } 
    else{ 
     printf("File Successfully Open\n"); 
    fprintf(fp,"%s*%s*%s*%s*%s*%s*%s#\n",myCust.idNumber,myCust.name,myCust.surname,myCust.address,myCust.telephone,myCust.mobile,myCust.email); 
    fclose(fp); 
    printf("Writing successfully completed and the file is closed!!\n"); 
    } 
} 
如果你想

我結構代碼這裏是(雖然我不認爲結構本身就是這個問題的原因)

struct customer 
{ 
    char idNumber[11]; 
    char name[11]; 
    char surname[15]; 
    char address[30]; 
    char telephone[14]; 
    char mobile[14]; 
    char email[21]; 


}; 
+1

這可能會被要求像一週20次。 – netcoder

+0

如果我是你,我不會在scanf中使用'&'來讀取C字符串。 –

回答

2
scanf("%s",&myCust.surname); 

scanf留下一個換行符輸入緩衝區

fflush(stdin); 

是標準定義的行爲,即使圖書館承諾它也不會在我的經驗中可靠地工作。

printf("\nEnter customer address : "); 
scanf("%[^\n]",&myCust.address); 

這會發現換行符。所以它不會讀取任何內容,因爲它首先遇到換行符。使其通過在格式的空間第一跳過空格,

scanf(" %[^\n]",&myCust.address); 

或者使用fgetsgetline(如果你是一個POSIX系統上)在整個行來讀取。

+0

fgets沒有工作,因爲它仍然被跳過(我忘了提及,在我的問題中,因爲我試過了 - 對不起) 但是,在地址scanf訣竅。謝謝你的回答 - 現在這一切都很有意義。 乾杯隊友 – alexeidebono

+0

如果您使用'fgets',則應該將其用於所有條目。因爲這會消耗換行符,所以下一個輸入不會立即找到。混合'scanf'和'fgets'幾乎不是一個好主意,因爲換行符的處理方式不同,會導致嚴重的頭痛。 –

+0

因爲fgets似乎是最好的選擇,所以我會真正採納你的意見。 – alexeidebono

1

標題:

嘗試讀取時正在跳過Scanf(),包括空格

是的。這不是一個錯誤。這就是scanf()的工作原理(請仔細閱讀下次嘗試使用的功能的文檔)。如果你想獲得一整行,不管其內容,請使用fgets()

char buf[1024]; 
fgets(buf, sizeof(buf), stdin); 
+0

只是嘗試這種方法 - 它仍然被跳過不幸 我嘗試了兩種方式 1,而不是在我通過了結構體變量上述情況下「BUF」 2.我用另一個字符(將其命名爲測試這個份),並試圖只是輸入數據(不通過它進一步到我的結構),它仍然跳過它 – alexeidebono

+0

@alexeidebono如何一點代碼清理?你確定你在正確的地方做這件事嗎? 'fgets()'實際上應該得到一整行,不管它是否包含空格。 – 2012-12-20 22:03:59

+0

雖然這工作 - scanf(「%[^ \ n]」,&myCust.address); (在開頭留有空格) – alexeidebono

0

如果正在跳過scanf()命令,那通常是因爲您輸入了先前掃描的垃圾。

嘗試在被跳過之前添加另一個scanf(&垃圾)。垃圾應該是char。