使用 txt 文件将输入发送到我的 C 程序

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);   
}  

该程序要求用户输入一定数量的数字,然后计算这些数字的平均值。我的问题是,如果我想使用一个名为 inputfile.txt 的文件来输入数据,我将如何在不从 STDIN 输入数据的情况下使用重定向?因此,数据来自 inputfile.txt。另外,我将如何设置 inputfile.txt?

您可以将数字放在一个文本文件中,每行一个。

然后,因为需要先输入计数,所以使用wc命令

$ 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

我使用大括号将 wc 和 cat 的输出分组为您程序的单个输入流。


一个bash-specific技巧:从文件中读取数字到一个shell数组中,然后用printf输出数组的长度和数组元素。

$ 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

只需创建一个内容兼容的文件即可。然后使用 < 重定向。例如文件内容为:

5
1
2
3
4
5

第一个数字是数字的数量。其他是您要计算平均值的数字。将此文件另存为任何名称,例如 file.txt,然后像这样调用您的程序:./a.out < file.txt.

你应该考虑 < 只是将文件内容重定向到标准输入。因此文件内容应该与从 stdin 交互地编写答案相同。如果您在文件中将第一个数字设置为 5,然后设置 4 个不同的数字,您的程序将要求第 5 个数字(抱歉)。您的程序不会要求第 5 个数字。查看评论。