Table of Contents
Detailed code explanation
Project Features
Learning gains
Code Testing
Future improvements
Summarize
Home Backend Development C++ Exercise C: Building a simple phonebook application

Exercise C: Building a simple phonebook application

Apr 03, 2025 pm 08:15 PM
c language ai switch c language programming 2025

Exercise C: Building a simple phonebook application

One of the best ways to learn C language programming is to practice it. This article will take you step through a project I recently completed: a simple phone book application. This app demonstrates file processing and basic data management in C, allowing you to add, view, and delete contacts.


Detailed code explanation

Here is the complete code:

 <code class="c">#include <stdio.h> #include <string.h> // 函数声明void addcontact(char name[], char number[]); void viewcontacts(); void deletecontact(char name[]); int main() { int choice; char name[20]; char number[20]; printf("-- 欢迎使用您的电话簿! -- \n"); do { // 显示菜单printf("\n您想执行什么操作?\n"); printf("1. 创建新联系人\t 2. 查看电话簿\t 3. 删除联系人\t 4. 退出\n"); scanf("%d", &choice); switch (choice) { case 1: // 添加新联系人printf("很好,让我们创建一个新联系人:\n"); printf("请输入联系人的姓名:\n"); scanf("%s", name); printf("现在输入电话号码:\n"); scanf("%s", number); addcontact(name, number); break; case 2: // 查看电话簿printf("这是您的电话簿:\n"); viewcontacts(); break; case 3: // 删除联系人printf("请输入要删除的联系人的姓名:\n"); scanf("%s", name); deletecontact(name); break; } } while (choice != 4); // 循环直到用户选择“退出” return 0; } // 向电话簿添加联系人的函数void addcontact(char name[], char number[]) { FILE *pfile; pfile = fopen("phonebook.txt", "a"); if (pfile == NULL) { printf("打开电话簿失败。"); return; } fprintf(pfile, "姓名: %s \t 电话: %s\n", name, number); printf("联系人已创建!\n"); fclose(pfile); } // 查看电话簿中所有联系人的函数void viewcontacts() { char filecontent[200]; FILE *pfile; pfile = fopen("phonebook.txt", "r"); while (fgets(filecontent, sizeof(filecontent), pfile)) { printf("\n%s", filecontent); } fclose(pfile); } // 从电话簿中删除联系人的函数void deletecontact(char name[]) { FILE *pfile, *ptrash; char line[200], contactname[20], contactnumber[20]; pfile = fopen("phonebook.txt", "r"); ptrash = fopen("trash.txt", "w"); if (pfile == NULL || ptrash == NULL) { printf("打开文件失败。"); return; } while (fgets(line, sizeof(line), pfile)) { sscanf(line, "姓名: %s \t 电话: %s\n", contactname, contactnumber); if (strcmp(name, contactname) != 0) { fputs(line, ptrash); } } fclose(pfile); fclose(ptrash); // 将旧电话簿替换为更新后的版本remove("phonebook.txt"); rename("trash.txt", "phonebook.txt"); printf("联系人已删除。"); }</string.h></stdio.h></code>
Copy after login

Project Features

This program implements three core functions:

  1. Add a contact:
    • Allows users to enter their name and phone number.
    • Store contact information in a file named phonebook.txt .
  2. View contact:
    • Read and display all contact information stored in the phonebook.txt file.
  3. Delete a contact:
    • Delete the contact based on the name entered by the user.
    • Filter out deleted contacts by creating temporary files and replace the original files.

Learning gains

Through this exercise, I consolidated the following C language knowledge:

  1. File processing: Proficient in using fopen , fclose and other file operation functions, and handle the failure of file opening.
  2. String operation: Use functions such as strcmp and sscanf to compare and parse strings.
  3. Basic Data Management: Learn how to store and manage data in simple text files, and update file content by creating temporary files.

Code Testing

  1. Copy the code into a .c file (e.g. phonebook.c ) and compile with a C compiler (e.g. GCC):
 <code class="bash">gcc -o phonebook phonebook.c</code>
Copy after login
  1. Run the compiled program:
 <code class="bash">./phonebook</code>
Copy after login
  1. Follow the on-screen prompts to add, view, or delete contacts.
  2. Open the phonebook.txt file to verify that the data is stored correctly.

Future improvements

This program is a good start and the following improvements can be considered in the future:

  1. Enter Verification: Verify the validity of the phone number (for example, including only numbers) to prevent duplicate names.
  2. User interface improvement: Provides clearer prompts, allowing input of names containing multiple words (using fgets instead of scanf ).
  3. Enhanced file processing: Consider data encryption for improved security, using more structured file formats such as CSV or JSON.
  4. Advanced Features: Add search function to sort contacts alphabetically.

Summarize

This exercise helped me understand the C language file processing and basic data management in the basics. This is a simple but practical program that can serve as the basis for more complex projects. If you are a beginner in C language, you highly recommend giving it a try! This is an interesting and rewarding learning process.

The above is the detailed content of Exercise C: Building a simple phonebook application. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the syntax for adding columns in SQL What is the syntax for adding columns in SQL Apr 09, 2025 pm 02:51 PM

The syntax for adding columns in SQL is ALTER TABLE table_name ADD column_name data_type [NOT NULL] [DEFAULT default_value]; where table_name is the table name, column_name is the new column name, data_type is the data type, NOT NULL specifies whether null values ​​are allowed, and DEFAULT default_value specifies the default value.

SQL Clear Table: Performance Optimization Tips SQL Clear Table: Performance Optimization Tips Apr 09, 2025 pm 02:54 PM

Tips to improve SQL table clearing performance: Use TRUNCATE TABLE instead of DELETE, free up space and reset the identity column. Disable foreign key constraints to prevent cascading deletion. Use transaction encapsulation operations to ensure data consistency. Batch delete big data and limit the number of rows through LIMIT. Rebuild the index after clearing to improve query efficiency.

How to set default values ​​when adding columns in SQL How to set default values ​​when adding columns in SQL Apr 09, 2025 pm 02:45 PM

Set the default value for newly added columns, use the ALTER TABLE statement: Specify adding columns and set the default value: ALTER TABLE table_name ADD column_name data_type DEFAULT default_value; use the CONSTRAINT clause to specify the default value: ALTER TABLE table_name ADD COLUMN column_name data_type CONSTRAINT default_constraint DEFAULT default_value;

Use DELETE statement to clear SQL tables Use DELETE statement to clear SQL tables Apr 09, 2025 pm 03:00 PM

Yes, the DELETE statement can be used to clear a SQL table, the steps are as follows: Use the DELETE statement: DELETE FROM table_name; Replace table_name with the name of the table to be cleared.

How to deal with Redis memory fragmentation? How to deal with Redis memory fragmentation? Apr 10, 2025 pm 02:24 PM

Redis memory fragmentation refers to the existence of small free areas in the allocated memory that cannot be reassigned. Coping strategies include: Restart Redis: completely clear the memory, but interrupt service. Optimize data structures: Use a structure that is more suitable for Redis to reduce the number of memory allocations and releases. Adjust configuration parameters: Use the policy to eliminate the least recently used key-value pairs. Use persistence mechanism: Back up data regularly and restart Redis to clean up fragments. Monitor memory usage: Discover problems in a timely manner and take measures.

phpmyadmin creates data table phpmyadmin creates data table Apr 10, 2025 pm 11:00 PM

To create a data table using phpMyAdmin, the following steps are essential: Connect to the database and click the New tab. Name the table and select the storage engine (InnoDB recommended). Add column details by clicking the Add Column button, including column name, data type, whether to allow null values, and other properties. Select one or more columns as primary keys. Click the Save button to create tables and columns.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

How to create an oracle database How to create an oracle database How to create an oracle database How to create an oracle database Apr 11, 2025 pm 02:33 PM

Creating an Oracle database is not easy, you need to understand the underlying mechanism. 1. You need to understand the concepts of database and Oracle DBMS; 2. Master the core concepts such as SID, CDB (container database), PDB (pluggable database); 3. Use SQL*Plus to create CDB, and then create PDB, you need to specify parameters such as size, number of data files, and paths; 4. Advanced applications need to adjust the character set, memory and other parameters, and perform performance tuning; 5. Pay attention to disk space, permissions and parameter settings, and continuously monitor and optimize database performance. Only by mastering it skillfully requires continuous practice can you truly understand the creation and management of Oracle databases.

See all articles