我正在 C 中创建一个函数 void N
,它读取一个文件,第 4 行然后每 6 行是一个数字,我需要将其从字符串转换为 double 并将它们放入新数组中。 .但是我偶然发现的每个新数字都会重写数组中所有现有的数字
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
void V(int *id,int i,int *praca, double *plat,int *datum, FILE **f)
{
char meno[2000],priezvisko[2000];
if ((*f = fopen("zam.txt", "r")) == NULL)
{
printf("Neda sa otvorit");
// koniec programu
return ;
}
while(//vypis informacii zamestnancov
fscanf(*f,"%d %s %s %d %lf %d",&id[i],&meno[i],&priezvisko[i],&praca[i],&plat[i],&datum[i])>0)
{
printf(" osobne cislo zamestnanca:%d\n meno priezvisko:%s %s\n administrativa/vyrobny pracovnik:%d\n plat:%g\n datum:%08d\n\n",id[i],&meno[i],&priezvisko[i],praca[i],plat[i],datum[i]);
i++;
}
}
void N(int i,double plat[], FILE *f)
{
rewind(f);
int j=0,k=0;
double *platy[1800];
char line[1800];
int suma = 0;
int count = 0;
int lineNumber = 3;
double val;
double d;
while(fgets(line, sizeof(line), f)!= NULL)
{
if (count == lineNumber)
{
suma++; //pocet platov
count++;
lineNumber+=6;
platy[i]=malloc(sizeof(line));
printf("i : %d\n",i);
//printf("%s",line);
val = atof(line);
//printf("%g\n",val);
platy[i] = &val;
val = *platy[i];
d = *platy[0];
printf("array: %g\n",val);
printf("array 0: %g\n",d);
i++;
}
else
{
count++;
}
printf("%d. %d\n",count,suma);
}
for (j=0 ; j<suma; j++) {
val = *platy[j];
printf("%g\n",val);
}
}
int main() //MAIN
{
int i=0,id[1800],praca[1800],datum[1800]; //deklaracie
char *meno[1800],*priezvisko[1800],z;
double plat[1800];
FILE *f;
while((z = getchar())!='K')
{
if(z == 'V')
V(id,i,praca,plat,datum,&f);
if(z == 'P')
P(i,praca,plat,datum,f);
if(z == 'N')
N(i,plat,f);
}
return 0;
}
最佳答案
这段代码根本就是错误的
double *platy[1800];
和
platy[i]=malloc(sizeof(line));
您声明了一个指向 double 的指针数组。然后设置一个数组元素以明确指向输入行的 malloc
d 内容。
我怀疑你想要的是
double platy[1800];
...
platy[i] = atof(line);
关于c - ‘While’不断重写数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40432632/