Possible Duplicate:
scanf: “%[^\n]” skips the 2nd input but “ %[^\n]” does not. why?
Basically I have a customer struct where I am to enter customer details, one of which is the address. Of course the address is a sentence since this is a basic text program without graphics.
I’m trying to use scanf("%[^\n]",&VARIABLE) method because that worked in previous programs.
However here , the input is being skipped. I tried to flush the buffer before I take this input but it did not make any difference. I also tried to create another string and pass my input to that and then copy the data to my struct and that did not work either.
Here is my code – The problem is occuring at the 4th scanf("%[^\n]",&myCust.address) : (NB: this is a work in progress so you might see some extra prints and stuff for now)
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");
}
}
if you want my struct code here it is ( although i dont think that the struct itself is the cause of this problem )
struct customer
{
char idNumber[11];
char name[11];
char surname[15];
char address[30];
char telephone[14];
char mobile[14];
char email[21];
};
This
scanfleaves a newline in the input bufferis undefined behaviour by the standard, and doesn’t work reliably in my experience even if the library promises it would.
This finds the newline immedaitely. So it doesn’t read anything in, because it first encounters a newline. Make it skip whitespace first by including a space in the format,
Or use
fgetsorgetline(if you’re on a POSIX system) to read in an entire line.