#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?
uj5u.com熱心網友回復:
你會把你的數字放在一個文本檔案中,每行一個。
然后,因為需要先輸入計數,所以使用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 的技術:將檔案中的數字讀入 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
uj5u.com熱心網友回復:
只需創建具有兼容內容的檔案。然后使用重定向<。例如,檔案內容為:
5
1
2
3
4
5
第一個數字是數字的數量。其他是您要計算平均值的數字。將此檔案保存為任何名稱file.txt,然后像這樣呼叫您的程式:./a.out < file.txt.
您應該考慮<的只是將檔案內容重定向到標準輸入。所以檔案內容應該與從標準輸入互動地寫答案相同。如果您在檔案中將第一個數字設定為 5,然后設定 4 個不同的數字,您的程式將要求輸入第 5 個數字(對不起)。您的程式不會要求第 5 個數字。看評論。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/453368.html
上一篇:在bash中轉義字符
下一篇:如何在回圈中使用sed?
