user6866732 user6866732 - 1 month ago 10
C Question

Display items from an input file

This program scans numbers from an input file.

In this case, the numbers are:
23
353
626
5
14
25
86
95
44
47
55
26
30
14
12
25
28
47
895
4255

The user can choose to display as many numbers as they want.

If the user wants to display the first 3 numbers then 23, 353 and 626 should be displayed.

The following code displays no numbers.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>

void FillArray(FILE *fp, int n, int num[]);

int main()
{
FILE *fptr;
FILE *outPtr;

int num[20];
int i;
int number = 0;
int sum = 0;

fptr = fopen("numInput.txt", "r");

FillArray(fptr, number, num);

for (i = 0; i < number; i++)
{
printf("%d\n", num[i]);
}

for (i = 0; i < number; i++)
{
sum = sum + num[i];
}
outPtr = fopen("resOut.txt", "w");
fprintf(outPtr, "The Sum is %d", sum);

fclose(fptr);
fclose(outPtr);

return 0;
}

void FillArray(FILE *fp, int n, int num[])
{
int count = 0;
printf("How many number? ");
scanf("%d", &n);

for (count = 0; count < n; count++)
{
fscanf(fp, "%d", &num[count]);
}

}

Answer

Compare (in your code):

int number = 0;

with (commented by me)

FillArray(fptr, number, num);     /* FillArray() will receive only COPIES of arguments */

for (i = 0; i < number; i++)
{
    printf("%d\n", num[i]);
}

How many times will body of this loop execute?

(Hint: The function FillArray() has no chance to change the value of number, so it is still 0.)

Recommended fixes (guaranteed) - based on using a pointer to number:

void FillArray(FILE *, int *, int *);        /* Insert explicit declaration in main() */
                                             /*    - only for my satisfaction ;-)     */

FillArray(fptr, &number, num);               /*      &number  instead of  number      */

void FillArray(FILE *fp, int *n, int num[])  /*        *n     instead of     n        */

    scanf("%d", n);                          /*         n     instead of    *n        */

    for (count = 0; count < *n; count++)     /*        *n     instead of     n        */

(and consider using plural in your prompt "How many number? ")