How do I pass a pointer value to an array of the struct;
For example, on a txt I have this:
John Doe;xxxx@hotmail.com;214425532;
My code:
typedef struct Person{
char name[100];
char email[100];
int phone;
}PERSON;
int main(){
PERSON persons[100];
FILE *fp;
char *ap_name;
char *ap_email;
char *ap_phone;
char line[100];
fp=("text.txt","r");
if(fp==NULL){
exit(1);
}
else{
fgets(line,100,fp);
ap_name=strtok(line,";");
ap_email=strtok(NULL,";");
ap_phone=strtok(NULL,";");
}
return 0;
}
My question is how can I pass the value of ap_name, ap_email, ap_phone to the struct?
And, do I need to use all of these pointers?
Name and email are relatively easy; just use
strcpy(orstrncpy);This will copy the contents of the string pointed to by
ap_nameinto the name field of the struct. At mostsizeof persons[i].name - 1(100 – 1, or 99) characters will be copied intopersons[i].name, and if the length of the string pointed to byap_nameis less than that, then 99 – strlen(ap_name) nul characters (ASCII 0) are appended. Same thing for email: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):
and then convert the string using
strtoul():The
strtoul()library function will convert a string representation of a number into the equivalent numerical value.