C语言写一段将学生姓名,学号,性别,电话号码录入,并实现靠学号检测是否有重复录入,性别为男或女,输出到一个文件
时间: 2023-04-02 17:04:44 浏览: 65
好的,这是一个关于 C 语言编程的问题。可以使用结构体来存储学生的信息,然后使用文件操作函数将信息写入文件。在录入学生信息时,可以使用循环来检测学号是否重复,如果重复则提示用户重新输入。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100
struct Student {
char name[20];
int id;
char gender[10];
char phone[20];
};
int main() {
struct Student students[MAX_STUDENTS];
int num_students = ;
// 读取已有学生信息
FILE *fp = fopen("students.txt", "r");
if (fp != NULL) {
while (fscanf(fp, "%s %d %s %s", students[num_students].name, &students[num_students].id, students[num_students].gender, students[num_students].phone) == 4) {
num_students++;
}
fclose(fp);
}
// 录入新学生信息
while (num_students < MAX_STUDENTS) {
printf("请输入学生姓名、学号、性别、电话号码(用空格分隔):\n");
scanf("%s %d %s %s", students[num_students].name, &students[num_students].id, students[num_students].gender, students[num_students].phone);
// 检测学号是否重复
int i;
for (i = ; i < num_students; i++) {
if (students[i].id == students[num_students].id) {
printf("学号已存在,请重新输入!\n");
break;
}
}
if (i == num_students) {
num_students++;
}
}
// 将学生信息写入文件
fp = fopen("students.txt", "w");
if (fp != NULL) {
int i;
for (i = ; i < num_students; i++) {
fprintf(fp, "%s %d %s %s\n", students[i].name, students[i].id, students[i].gender, students[i].phone);
}
fclose(fp);
}
printf("学生信息已保存到文件!\n");
return ;
}
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)