#include<stdio.h>
int main()
{
int n, count = 1;
float x, average, sum = 0;
printf("How many numbers do you wish to test: ");
scanf ("%d",&n);
while (count <= n)
{
printf ("Enter number #%d: ",count);
scanf("%f", &x);
sum += x;
++count;
}
average = sum/n;
printf("\nThe Average is: %.2f\n", average);
}
This program asks the user for a certain amount of numbers to be entered and then calculates the average of those numbers. My question is, if I want to use a file called inputfile.txt to input the data, how would I use redirection without typing in the data from STDIN? So instead the data comes from the inputfile.txt. Also how would I set up the inputfile.txt?
>Solution :
You’d put your numbers in a text file, one per line.
Then, because you need to enter the count first, use the wc command
$ gcc your_code.c
$ cat numbers
10
20
40
$ { wc -l < numbers; cat numbers; } | ./a.out
How many numbers do you wish to test: Enter number #1: Enter number #2: Enter number #3:
The Average is: 23.33
I use the braces to group the output of both wc and cat into a single input stream for your program.
A bash-specific technique: read the numbers from the file into a shell array, and then use printf to output the length of the array and the array elements.
$ readarray -t nums < numbers
$ printf '%d\n' "${#nums[@]}" "${nums[@]}" | ./a.out
How many numbers do you wish to test: Enter number #1: Enter number #2: Enter number #3:
The Average is: 23.33