用C语言,实现姓名、学号、手机号的输入,保存至文件(通讯录.txt),查看已保存的通讯信息。
时间: 2025-06-14 08:16:04 浏览: 10
在C语言中,你可以使用`stdio.h`库来进行输入操作,`fstream`库进行文件的读写操作。这里是一个简单的示例,展示了如何实现姓名、学号和手机号的输入,并将数据保存到`通讯录.txt`文件中,以及如何从该文件中读取并显示已保存的信息。
首先,创建一个结构体来存储个人信息:
```c
#include <stdio.h>
#include <string.h>
typedef struct {
char name[50];
int student_id;
char phone_number[15];
} Contact;
void input_contact(Contact* contact) {
printf("请输入姓名:");
fgets(contact->name, sizeof(contact->name), stdin);
contact->name[strcspn(contact->name, "\n")] = '\0'; // 清除换行符
printf("请输入学号:");
scanf("%d", &contact->student_id);
printf("请输入手机号:");
scanf("%s", contact->phone_number);
}
void save_to_file(const char* filename, Contact* contact) {
FILE* file = fopen(filename, "w");
if (file) {
fprintf(file, "%s %d %s\n", contact->name, contact->student_id, contact->phone_number);
fclose(file);
printf("联系人信息已保存到文件。\n");
} else {
printf("无法打开文件。\n");
}
}
void read_from_file(const char* filename) {
FILE* file = fopen(filename, "r");
if (file) {
char line[100];
while (fgets(line, sizeof(line), file)) {
Contact contact;
sscanf(line, "%[^ \t] %d %[^ \t]", contact.name, &contact.student_id, contact.phone_number);
printf("姓名:%s 学号:%d 手机号:%s\n", contact.name, contact.student_id, contact.phone_number);
}
fclose(file);
} else {
printf("无法打开文件。\n");
}
}
```
然后,你可以像这样使用这些函数:
```c
int main() {
Contact new_contact;
input_contact(&new_contact);
save_to_file("通讯录.txt", &new_contact);
// 如果需要查看已保存的联系人信息
read_from_file("通讯录.txt");
return 0;
}
```
注意:这个例子假设输入的手机号码不会超过14个字符(包括区号),并且用户输入的内容不会有特殊字符。实际应用中应加入更详细的错误检查和验证。
阅读全文
相关推荐



















