在C中的文件中打印一个int数组

时间:2015-03-31 17:45:35

标签: c arrays file int

我需要为学生和每个成绩写一个文件(不是二进制文件)(在此表格下注[10])。我没有收到任何错误,但是当我尝试编写文件时,只打印了最后一个成绩,而且我不知道如何打印整个列表。例如(int nr_note表示学生有多少年级),如果学生成绩为6,8,9,则只打印9。 先感谢您。

#include <stdio.h>
#include <stdlib.h>

struct student{
    int nr_matricol;
    char nume[10];
    int nr_note;
    int note[10];
};

void citire_date(struct student *studenti, int n, FILE *f){
    int i, j;

    for(i=0;i<n;i++){
        printf("Studentul %d\n", i+1);
        printf("Numarul matricol: "); scanf("%d", &(studenti+i)->nr_matricol);
        printf("Numele studentului: "); fflush(stdin); gets((studenti+i)->nume);
        printf("Numarul de note: "); scanf("%d", &(studenti+i)->nr_note);
        for(j=0;j<((studenti+i)->nr_note);j++){
            printf("Nota %d: ", j+1); scanf("%d", &(studenti+i)->note[i]);
        }
        fprintf(f, "Numar matricol: %d\nNume: %s\nNote: %d \n", ((studenti+i)->nr_matricol) ,((studenti+i)->nume), ((studenti+i)->note[i]));
    }
}

int main()
{
    struct student studenti[20];
    FILE *f;
    int n;

    f = fopen("studenti.txt", "w");
    if(f==NULL){
        printf("Nu s-a putut deschide/crea fisierul pentru scriere.");
        exit(1);
    }

    printf("Introduceti numarul de studenti: "); scanf("%d", &n);
    citire_date(studenti, n, f);
    fclose(f);


    return 0;
}

1 个答案:

答案 0 :(得分:0)

像这样更改citire_date()功能:

void citire_date(struct student *studenti, int n, FILE *f){
int i, j;

for(i=0;i<n;i++){
    printf("Studentul %d\n", i+1);
    printf("Numarul matricol: "); scanf("%d", &(studenti+i)->nr_matricol);
    printf("Numele studentului: "); fflush(stdin); gets((studenti+i)->nume);
    printf("Numarul de note: "); scanf("%d", &(studenti+i)->nr_note);
    for(j=0;j<((studenti+i)->nr_note);j++){
        printf("Nota %d: ", j+1); scanf("%d", &(studenti+i)->note[j]);
    }
    fprintf(f, "Numar matricol: %d\nNume: %s\n", ((studenti+i)->nr_matricol) ,((studenti+i)->nume) );
    // Printing the notes
    for(j=0;j<((studenti+i)->nr_note);j++){
        fprintf(f, "Note: %d = %d \n", j+1, ((studenti+i)->note[j]));
    }
}

}

您需要使用循环打印所有笔记。