Pointer arithmetic works with structure, and you should definitely be using iteration rather than creating separate functions a youve done. You should soon find that scanf i not very good for getting and validating user input. Also, you should be starting to add some input validation so that bogu user input cannot make your programs misbehave. Ive seen in your recent question that youre taking advice, learning how things work, and progressing nicely in your C ability. Keep it up. Here are some suggestion to make your program better:
#include #include #include
#define MAX_STR_LEN 32 #define NUM_PEOPLE 2
typedef struct char firstName[MAX_STR_LEN]; int age; person_t;
void getPersonInfo(person_t *); void displayPersonInfo(const person_t *); void displayAllPeople(const person_t *, size_t);
void getPersonInfo(person_t *ptr) char in[MAX_STR_LEN], *p;
do printf("Enter the name: "); fget(ptr->firstName, MAX_STR_LEN, stdin); while (strlen(ptr->firstName) <= 1); if ((p = strchr(ptr->firstName,\\n)) != NULL) *p = \\0; do printf("Enter the age: "); fgets(in, MAX_STR_LEN, stdin); while (sscanf(in, "%d",&(ptr->age)) != 1); puts("");
void displayPersonInfo(const person_t *ptr) printf("The first name is %s\\n", ptr->firstName); printf("Age is %d\\n\\n", ptr->age);
void displayAllPeople(const person_t *p, size_t n) size_t i = 0;
while (i++ < n) displayPersonInfo(p++);
int main(int argc, char *argv[]) person_t people[NUM_PEOPLE], *p = people; size_t i;
for (i = 0; i < NUM_PEOPLE; i++) getPersonInfo(p++); displayAllPeople(people, NUM_PEOPLE); return 0;
#if 0
Sample run:
Enter the name: Mary Enter the age: 16
Enter the name: Joe Enter the age: 20
The first name i Mary Age i 16
The first name is Joe Age is 20
#endif
|