Possible Duplicate:
How do you allow spaces to be entered using scanf?
How can I scan strings with spaces in them using scanf()?
New to C and I feel this should be very simple but for some reason I’m not seeing the clear answer.
Trying to write a name and address to a file but if I put ‘FirstName LastName’ only FirstName gets entered into the file. Same with address. Is there a way to accept the whole name with the space into the file?
struct person{
char name[20];
char address[50];
char telno[20];
} info;
fp=fopen("contacts","a")
printf("Enter Name : ");
scanf("%s",info.name);
printf("Enter Address : ");
scanf("%s",info.address);
fprintf(fp,"%20s %20s %20s",info.name,info.address,info.telno);
fclose(fp);
New to C so please excuse my ignorance. Thanks.
The only way to read “white space” in to a string with
scanf()is with the negated scanset:In general the answer you’re going to get however is to “not use scanf” and use
fgets()instead:Don’t forget a lot of this info for scanf() and fgets() and others is easy to get with a quick search.
Edit:
I tried replacing scanf with fgets but when I run the program it skips past the "Enter Name:"If it’s “skiping” by your
fgets()that means that yourfgets()just read a left over character that was sitting on thestdinbuffer. I’d wager a guess it was a newline character.When you enter a string:
You’re getting a newline
'\n'appended to the end after the'h'. That meansscanf()is going to read the letters and leave the newline,fgets()on the other hand will read everything up to/including the newline. So if you were to do this:The
fgets()would appear to be “skipped”. If you’re saying replacing both withfgets()is skipping the first one, then yourstdinbuffer isn’t clean and you must have something before hand leaving a newline character on it.