# C++ 将多项式从文件.txt加载到终端时出现问题

polynom* vytvorZeSouboru(const char *soubor, int *pocet) {
FILE *file = fopen(soubor, "r");

if (file == NULL) {
perror("Chyba pri otevirani souboru");
exit(EXIT_FAILURE);
}

// Number of polynomials in the file - set to 0 at the beginning
*pocet = 0;

// Find out how many rows (polynomials) are in the file
int c;
while ((c = fgetc(file)) != EOF) {
if (c == '\n') {
(*pocet)++;
}
}

// Let's go back to the beginning of the file
rewind(file);

// Pole polynomů
Polynom *polePolynomu = (Polynom*)malloc(*pocet * sizeof(Polynom));

//  Reading polynomials from a file
for (int i = 0; i < *pocet; ++i) {
int pocetKoeficientu;
if (fscanf(file, "%d", &pocetKoeficientu) != 1) {
fprintf(stderr, "Chyba pri cteni poctu koeficientu polynomu ze souboru.\n");
exit(EXIT_FAILURE);
}

// Polynomial initialization
polePolynomu[i].koeficienty = (int*)malloc(pocetKoeficientu * sizeof(int));
polePolynomu[i].pocetKoeficientu = pocetKoeficientu;

// Načtení koeficientů polynomu
for (int j = 0; j < pocetKoeficientu; ++j) {
if (fscanf(file, "%d", &polePolynomu[i].koeficienty[j]) != 1) {
fprintf(stderr, "Chyba pri cteni koeficientu polynomu ze souboru.\n");
exit(EXIT_FAILURE);
}
}
}

// Zavření souboru
fclose(file);

return polePolynomu;
}

void vypisPolynomy(const Polynom *polePolynomu, int pocet) {
for (int i = 0; i < pocet; ++i) {
printf("Polynom %d: ", i + 1);
for (int j = 0; j < polePolynomu[i].pocetKoeficientu; ++j) {
printf("%d ", polePolynomu[i].koeficienty[j]);
}
printf("\n");
}
}

int main() {
int pocet, i;

const char *cestaKSouboru = "vytvorZeSouboru.txt";

Polynom *polePolynomu = vytvorZeSouboru(cestaKSouboru, &pocet);

vypisPolynomy(polePolynomu, pocet);

// Memory release
for (int i = 0; i < pocet; ++i) {
free(polePolynomu[i].koeficienty);
}
free(polePolynomu);
}


## 推荐答案

Line count

*pocet = 0;
int prior = '\n';
int c;
while ((c = fgetc(file)) != EOF) {
if (prior == '\n') {
(*pocet)++;
}
prior = c;
}