Name and email are relatively easy; just use strcpy
(or strncpy
);
strncpy(persons[i].name, ap_name, sizeof persons[i].name - 1);
This will copy the contents of the string pointed to by ap_name
into the name field of the struct. At most sizeof persons[i].name - 1
(100 - 1, or 99) characters will be copied into persons[i].name
, and if the length of the string pointed to by ap_name
is less than that, then 99 - strlen(ap_name) nul characters (ASCII 0) are appended. Same thing for email:
strncpy(persons[i].email, ap_email, sizeof persons[i].email - 1);
Note that this assumes that the length of ap_name and ap_email will always be less than the destination buffers; as written, your code pretty much guarantees this, but extra sanity checking may not be a bad idea.
As for the phone number, a regular int may not be (and most likely won't be) wide enough to hold a 10-digit number, assuming you're storing area code or extensions (the minimum range guaranteed by the language standard is [-32767,32767]
). Not to mention that phone numbers are generally represented with non-numeric characters, such a (999)-999-9999
. You may want to store this information as a string as well.
EDIT
Another alternative for the phone number is to use a wider numeric type (preferably unsigned):
struct PERSON {
...
unsigned long phone;
...
};
and then convert the string using strtoul()
:
persons[i].phone = strtoul(ap_phone, NULL, 10);
The strtoul()
library function will convert a string representation of a number into the equivalent numerical value.