您好,我的功能有问题。基本上我需要将多项式从 file.txt 加载到终端。 基本上,我每行都有几个系数,1 个多项式等于 1 行。当我在终端上尝试输出时很奇怪。 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);
// Reading polynomials from a file
for (int i = 0; i < *pocet; ++i) {
int pocetKoeficientu;
... } // 进一步使用“pocetKoeficientu”
稍后使用变量“int pocetKoeficientu;”超出范围(仅在 for 循环内有效)。将其放在 for 循环的开头: // 从文件中读取多项式 int pocetKoeficcientu; 对于 (int i = 0; i < *pocet; ++i) { ... } // further use of "pocetKoeficientu"