someonehere
someonehere

Reputation: 1

program doesn't read a file properly

For homework I have to write a program where I am typing the string of n integer and then the program that prints the string,calculates the arithmetic mean and makes a new file only with even numbers and at the end prints the new file on screen.

And here are 2 programs

#include<stdio.h>
main()
{
    int x,n,i;
    FILE *p;
    p=fopen("podaci.dat","wb");
    printf("n=");
    scanf("%d",&n);
    fwrite(&n,sizeof(int),1,p);
    for(i=0;i<n;i++)
    {
        printf("x=");
        scanf("%d",&x);
        fwrite(&x,sizeof(int),1,p);
    }

    fclose(p);
}
#include<stdio.h>
void stampa(int n,int a[])
{
    int i;
    for(i=0;i<n;i++)
    printf("%5d",a[i]);
    printf("\n");

}


float ars(int n,int a[])
{
int i,s=0;
float ars=0;
for(i=0;i<n;i++)
s+=a[i];
return 1.0*s/n;
}


main()
{
    int i,n;
    FILE *p,*u;
    u=fopen("niz.dat","wb");
    p=fopen("podaci.dat","rb");
    fread(&n,sizeof(int),1,p);
    printf("n=%d\n",n);
    int a[n],m=0;
    for(i=0;i<n;i++)
    {
        fread(&a[i],sizeof(int),1,p);
        if(a[i]%2==0)
        {
            m+=1;

        }
        fwrite(&m,sizeof(int),1,u);
        for(i=0;i<n;i++)
        if(a[i]%2==0)
        {
            fwrite(&a[i],sizeof(int),1,u);
        }
        stampa(n,a);
        printf("ars=%.2f",ars(n,a));
        fclose(p);
        fclose(u);
    }

}

When I type more than 2 numbers the program instead of those numbers reads them as 0 and sometimes it adds numbers.

Upvotes: 0

Views: 40

Answers (1)

Tony Barletta
Tony Barletta

Reputation: 385

You cannot declare an array a[n] where n is a variable (number that you don't know at compile time but only once you read the file).

You can ether declare a[N] where N is a number big enough defined in with #DEFINE

#include <stdio.h>
#include ...

#DEFINE N 10000
//...
int a[N];

or you have to allocate a[] dynamically

int * a;
a = (int*)malloc(sizeof(int)*n);

You can read more about this here and here

Upvotes: 1

Related Questions