可能重複:這
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];
};
這可能會被要求像一週20次。 – netcoder
如果我是你,我不會在scanf中使用'&'來讀取C字符串。 –