Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use a txt file to send input to my C program

#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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading