I am trying to take input data and print it using structures. when i run this code it is not taking input for lastname. It directly asks to enter input for firstname. Can someone help me with this. Thank you.
address.c
typedef struct
{
char lname[25];
char fname[20];
char address[20];
char phonenumber[20];
}addressbook;
addressbook a;
int main()
{
printf("enter details:\n");
printf("enter lastname:\n");
gets(a.lastname);
printf("enter firstname:\n");
gets(a.firstname);
printf("enter address:\n");
gets(a.address);
printf("enter phone number:\n");
gets(a.phonenumber);
printf("lastname:%s\n",a.lastname);
printf("firstname: %s\n", a.firstname);
printf("address:%s\n", a.address);
printf("phone number:%s\n", a.phonenumber);
}
When I run this it is not waiting to enter the lastname. it directly goes to enter firstname.
That code won't even compile as it stands, producing (in my environment):
You should always (at least initially) compile with a high warning level and take note of what the compiler is telling you:
stdio.h
if you're going to useprintf
andgets
.In addition, you may want to consider the following:
int main()
is not one of the two canonical forms of themain
function. While the standard allows for implementation-defined extra ones, the "correct" one for this particular case would beint main (void)
.gets
is a dangerous function since there is no way to prevent buffer overflow, making your code insecure. For example, if I entered a thousand characters for my first name, it may well screw up your program by overwriting huge chunks of accounting information on the stack (like return addresses for example). You can find a safer input function here.Making most of those changes, you would end up with something like:
which compiles and runs okay, although it still has the serious buffer overflow vulnerability. If you want to fix that, you can refer to the link I gave.