我的功能有问题.基本上,我需要将多项式从file.txt加载到终端.
基本上,我在每行上有几个系数,1个多项式等于1行.当我在终端上try 我的输出是奇怪的.1系数不打印,3行/3多项式也不打印.
下面是我的函数:
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);
}