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

时间:2016-03-10 17:30:11

标签: c arrays file io

Goodday,当我输入学生的第一个名字时,程序会立即崩溃。此外,我不确定如何将名称和ID添加到数组中以打印到文本文件。我可以请一些帮助吗?

    scope.slideMenuToggle = function () {
        scope.slideMenu = !scope.slideMenu;
    };

2 个答案:

答案 0 :(得分:1)

代码仅为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);
}

答案 1 :(得分:0)

假设student.fname是一个足够大小的char数组

    scanf("%s", student.fname[i]);

应该是

scanf("%s", student.fname);

您需要将指针一个接一个地传递给数组的开头,而不是字符的值。 scanf将在一次通话中输入整个名称。