
這是格式化的 C 程序,名為 fahr_kel:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
int main( int argc, char *argv[] )
{
if (argc < 3)
{
std::cerr << "Usage:" << argv[0] << " arg1 arg2 \n"
<< "arg1 is the conversion type (1 or 2) \n "
<< "arg 2 is the temp to be converted" << std::endl;
return 1;
}
// Assign the variables used in this program
int temp, conv_temp, conv_type;
// assign the input options to variables
conv_type=atoi(argv[1]);
temp=atoi(argv[2]);
// convert the temps..
// if the input number is 1, convert from Kelvin to Fahrenheit
// if the input number is anything else, convert from Fahrenheit to Kelvin
if (conv_type == 1)
conv_temp = (((temp - 273) * 1.8) + 32);
else
conv_temp = (((( temp - 32 ) * 5 ) / 9 ) + 273 );
// print the data
printf (" %3.1i %3.1i\n",temp,conv_temp);
// end of main function
return 0;
}
我需要根據 bash 腳本中的使用者輸入來操作該程式。
這是我需要透過名為project3.data的C程式傳遞的資料檔案:
0
32
100
212
108
1243
3000
85
22
2388
235
這是我啟動的名為project3.bash 的腳本。
#!/bin/bash
echo -n "Convert from kelvin to fahrenheit(1) or fahreinheit to kelvin(2)"
read choice
/home/username/project3/fahr_kel [ choice project3.data ]
我只得到腳本輸出的第一行。 0 和 256
輸出需要如下圖所示:
---------------------- -----------------------
Fahrenheit Temperature Kelvin Temperature
--------------------- -----------------------
0 256
--------------------- -----------------------
32 273
---------------------- -----------------------
100 310
---------------------- -----------------------
212 373
---------------------- -----------------------
108 315
---------------------- -----------------------
1243 945
---------------------- -----------------------
3000 1921
---------------------- -----------------------
85 302
---------------------- -----------------------
22 268
---------------------- -----------------------
2388 1581
---------------------- -----------------------
235 385
---------------------- -----------------------
答案1
您的 C++ 程式會根據需要轉換溫度,並期望溫度值作為第二個輸入參數。但是,您的 bash 腳本不會將溫度作為輸入參數傳遞。相反,它使用以下命令呼叫 C++ 程序資料檔名作為輸入參數。這是不希望的。您應該使用輸入值本身作為參數來呼叫 C++ 程式;即您需要如下修改bash腳本。
bash 腳本中必要的修復是為每個資料行呼叫一次 c 函數,並添加必要的格式。我在下面展示了這一點。
#!/bin/bash
inputFile="project3.data"
echo -n "Convert from kelvin to fahrenheit(1) or fahreinheit to kelvin(2)"
read choice
# run the following per input data line
#./fahr_kel [ choice project3.data ]
cmd="./fahr_kel $choice "
# print header
linePrint="------------------ ----------------"
echo $linePrint
echo "Fahrenheit Temperature Kelvin Temperature"
echo $linePrint
while read inputVal
do
$cmd $inputVal
echo $linePrint
done < "$inputFile"
echo $linePrint
另一種方法是更改 C++ 程式以期望檔案輸入而不是溫度輸入。