Mình có một bài tập là tạo hàm nhập vào thông tin sinh viên theo mảng cấu trúc, sau đó ghi ra file .txt và đọc file đó. Thiệt tình là mình không biết sai chỗ nào, xuất bằng for() trong hàm main thì bị lỗi Thiếu chữ (N), xuất bằng hàm Xuat thì cũng bị lỗi đó và thêm lỗi xuống dòng. Xin các cao nhân góp ý kiến
Đây là code của mình:
#include<stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
typedef struct {
int id;
char fname[35];
char finame[10];
float p;
}sinhvien;
//Ham nhap va ghi File
void Nhap()
{
sinhvien *sv;
FILE *taptin = NULL;
errno_t err;
int i = 0;
sv = (sinhvien*)malloc(sizeof(sinhvien));
int maso = 0;
err = fopen_s(&taptin, "danhsachsinhvien.txt", "w");
if (taptin != NULL)
{
while (maso != -1)
{
printf("\nNhap vao MSSV. Nhap (-1) de ket thuc: ");
scanf_s("%d", &maso);
while (getchar() != '\n' && getchar() != EOF) {}
if (maso != -1)
{
sv[i].id = maso;
printf("\nNhap vao Ho va ten: ");
gets_s(sv[i].fname);
printf("\nNhap vao diem trung binh tich luy: ");
scanf_s("%f", &sv[i].p);
fprintf(taptin, "%5d%25s%5.2f\n", sv[i].id, sv[i].fname, sv[i].p);
i++;
sv = (sinhvien*)realloc(sv, (i + 1) * sizeof(sinhvien));
}
else break;
}
}
fclose(taptin);
}
//Ham doc FILE
sinhvien *Read(int *n)
{
sinhvien *sv;
FILE *taptin = NULL;
errno_t err;
int i = 0;
sv = (sinhvien*)malloc(sizeof(sinhvien));
err = fopen_s(&taptin, "danhsachsinhvien.txt", "r");
if (taptin != NULL)
{
while (!feof(taptin))
{
fscanf_s(taptin, "%d%f", &sv[i].id, &sv[i].p);
fgets(sv[i].fname, 100, taptin);
i++;
sv = (sinhvien*)realloc(sv, (i + 1) * sizeof(sinhvien));
}
}
else return 0;
i--;
*n = i;
fclose(taptin);
return sv;
}
void Xuat(sinhvien *sv, int *n)
{
int i;
printf("\nDanh sach sinh vien\n");
for (i = 0; i < *n; i++)
{
printf("%5d%25s%5.2f\n", sv[i].id, sv[i].fname, sv[i].p);
}
}
int main()
{
sinhvien *sv;
int n = 0;
//Nhap();
sv = Read(&n);
Xuat(sv, &n);
/*for(int i = 0; i < n; i++)
printf("%5d%25s%5.2\n", sv[i].id, sv[i].fname, sv[i].p);*/
printf("\n%d", n);
free(sv);
_getch();
return 0;
}



83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?