gpt4 book ai didi

c - 如何将字符串和整数添加到数组然后打印到文本文件

转载 作者:行者123 更新时间:2023-11-30 19:13:06 25 4
gpt4 key购买 nike

早上好,当我输入学生的名字时,程序立即崩溃。另外,我不太确定如何将名称和 ID 添加到数组中以打印到文本文件。我可以帮忙吗?

struct records{
int id;
char fname[15];
char lname[15];
};
struct records student;


int max=1000;
int i;
srand( time(NULL) ); //random numbers generated
ATND= fopen("Student Record.txt","a");
if(ATND== NULL){
printf("ERROR!");
exit(1);
}
for(i=0; i<100; i++){
printf("Enter student\'s first name: ");
scanf("%s", student.fname[i]);

printf("\n\n");
printf("Enter student\'s last name: ");
scanf("%s", student.lname[i]);

/*randomnumber*/student.id[i]=rand() %max + 39048543;

fprintf(ATND,"%s %s %d", student.fname[i], student.lname[i], student.id[i]);
}
fclose(ATND);

最佳答案

代码仅提供 1 条记录的数据空间,而它似乎需要 1000 条记录。其他问题的数量。怀疑10个小时后,OP已经完成了其中的一些

//Definition - good
struct records {
int id;
char fname[15]; // IMO 15 is too limiting for first and last
char lname[15];
};

// Only 1 student, need many more
// struct records student;
#define STUDENT_N 1000
struct records student[STUDENT_N];

void read_records(void) {
// avoid magic numbers
// int max = 1000;
int max = STUDENT_N;

int i;
srand(time(NULL)); //random numbers generated

// ATND not declared
FILE *ATND;

ATND = fopen("Student Record.txt", "a");
if (ATND == NULL) {
printf("ERROR!");
exit(1);
}

char buf[100];

// avoid magic numbers
// for (i = 0; i < 100; i++) {
for (i = 0; i < STUDENT_N; i++) {

printf("Enter student\'s first name: ");
// don't use scanf()
// scanf("%s", student.fname[i]);
if (fgets(buf, sizeof buf, stdin) == NULL) break;
if (sscanf(buf, "%14s", student[i].fname) != 1) break;

printf("\n\n");
printf("Enter student\'s last name: ");
// Add flush to insure buffered prompts that do not end in \n are sent
fflush(stdout);

// scanf("%s", student.lname[i]);
if (fgets(buf, sizeof buf, stdin) == NULL) break;
if (sscanf(buf, "%14s", student[i].lname) != 1) break;

// /*randomnumber*/student.id[i] = rand() % max + 39048543;
/*randomnumber*/student[i].id = rand() % max + 39048543;

// Do not index the name, index the structure
// fprintf(ATND, "%s %s %d", student.fname[i], student.lname[i], student.id[i]);
fprintf(ATND, "%s %s %d", student[i].fname, student[i].lname, student[i].id);
}
fclose(ATND);
}

关于c - 如何将字符串和整数添加到数组然后打印到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35923306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com