Function to Display a Contact
Part of the Logic & Flow section of Coddy's C journey — lesson 53 of 63.
Challenge
EasyBuilding on your contact management system from the previous lessons, create a function that displays contact information in a formatted way. This lesson introduces three new string functions you will need: fgets(), strcspn(), and strchr() — each is explained below before the requirements.
New functions used in this lesson:
fgets(buffer, size, stdin)— reads a line of input including spaces (unlikescanf, which stops at whitespace). It stores the input intobuffer, reading at mostsize - 1characters. It also stores the newline character'\n'at the end.strcspn(str, "\n")— returns the index of the first occurrence of'\n'instr. Used to remove the trailing newline left byfgets:str[strcspn(str, "\n")] = '\0';strchr(str, ch)— searches for the characterchinstrand returns a pointer to its location, orNULLif not found.
Your program should:
- Use the same
Contactstruct definition from the previous lessons with members:- A character array
namewith size 50 - A character array
phonewith size 20 - A character array
emailwith size 40 - An integer
age
- A character array
- Use the same
createContactfunction from previous lessons that:- Dynamically allocates memory for a
Contactstruct - Initializes all members to default values
- Returns a pointer to the contact
- Dynamically allocates memory for a
- Write a
populateContactfunction that:- Takes a pointer to a
Contactstruct as its parameter - Uses
fgets()to read each string field (name, phone, email) so that names with spaces are accepted - Uses
strcspn()to remove the trailing newline from each string field after reading it - Uses
scanf("%d", ...)to read the integer age field - Note: This version of
populateContactdoes not include phone number length validation — do not add it, as the test inputs use short phone numbers like555-1234
- Takes a pointer to a
- Write a function named
displayContactthat:- Takes a constant pointer to a
Contactstruct as its parameter:const struct Contact *contactPtr - Returns nothing (void)
- Prints the contact information in this exact format:
=== CONTACT DETAILS ===Name: [name]Phone: [phone]Email: [email]Age: [age] years old========================
- After displaying the basic information, calculates and displays additional details:
- Calculates the length of the name using
strlen()and prints:Name length: [length] characters - Determines the generation category based on age and prints:
- If age is between 0 and 12:
Generation: Child - If age is between 13 and 19:
Generation: Teenager - If age is between 20 and 39:
Generation: Young Adult - If age is between 40 and 59:
Generation: Middle-aged Adult - If age is 60 or above:
Generation: Senior
- If age is between 0 and 12:
- Checks if the email contains the character
'@'usingstrchr()and prints:- If
'@'is found:Email format: Valid - If
'@'is not found:Email format: Invalid
- If
- Calculates the length of the name using
- Takes a constant pointer to a
- In the main function:
- Create a contact using the
createContactfunction - Check if contact creation was successful
- Call the
populateContactfunction to fill in the contact data - Call the
displayContactfunction to show the formatted contact information - Free the dynamically allocated memory
- Print
Program completed successfully
- Create a contact using the
This challenge demonstrates how to create a display function that takes a constant pointer to a struct, ensuring that the function cannot modify the original data. You'll practice using fgets() to read strings that contain spaces, strcspn() to strip trailing newlines, the arrow operator to access struct members through a pointer, strchr() for character searching, and conditional logic for data categorization. The use of const in the parameter declaration is a good practice that prevents accidental modification of the contact data within the display function.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
char phone[20];
char email[40];
int age;
} Contact;
Contact* createContact() {
Contact* contact = (Contact*)malloc(sizeof(Contact));
if (contact == NULL) {
return NULL;
}
strcpy(contact->name, "");
strcpy(contact->phone, "");
strcpy(contact->email, "");
contact->age = 0;
return contact;
}
void populateContact(Contact* contactPtr) {
printf("Enter name: ");
scanf("%s", contactPtr->name);
printf("Enter phone: ");
scanf("%s", contactPtr->phone);
printf("Enter email: ");
scanf("%s", contactPtr->email);
printf("Enter age: ");
scanf("%d", &contactPtr->age);
if (contactPtr->age < 0 || contactPtr->age > 120) {
printf("Invalid age entered\n");
} else if (strlen(contactPtr->phone) < 10) {
printf("Invalid phone number\n");
} else {
printf("Contact populated successfully\n");
}
}
int main() {
Contact* contact = createContact();
if (contact == NULL) {
return 1;
}
populateContact(contact);
printf("Contact Information:\n");
printf("Name: %s\n", contact->name);
printf("Phone: %s\n", contact->phone);
printf("Email: %s\n", contact->email);
printf("Age: %d\n", contact->age);
free(contact);
printf("Contact deleted successfully\n");
return 0;
}All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions6Memory Management
Stack vs. Heap MemoryDynamic Allocation - malloc()Using sizeof() for AllocationChecking Allocation FailureFreeing Memory with free()Allocating with calloc()Recap: Dynamic Array9Project: Simple Contact Entry
Project: Define Contact StructFunction to Create a Contact