[英]Reading function from txt file in C?
我有數值積分程序,我想從文本文件中讀取函數,並使用后綴算法計算該函數。 我的問題是,如何從文件中讀取sin
, log
等,並將它們放入array.For數字中,我可能會使用strtol()
函數,如下所示:
int main(){
int i;
char *str = "ab234 56 cid*(s349*(20kd", *p = str;
while (*p) {
if (isdigit(*p)) {
long val = strtol(p, &p, 10);
printf("%ld\n", val);
} else {
p++;
}
}
}
好吧,您不能僅僅從字符串sin
開始神奇地計算正弦函數。 您必須編寫代碼才能做到這一點。
我建議將輸入拆分為令牌(也許僅在循環中使用strtok()
),然后檢查每個令牌。
對於數字,將數字壓入堆棧(由於您提到函數/運算符為后綴,所以我假設您需要一個堆棧)。
對於字符串(函數名),看看他們在一個硬編碼表或if
-series並做了評價。
就像是:
char **tokens = ... // NULL-terminated list of input tokens
int i = 0;
while(tokens[i] != NULL)
{
if(isdigit(tokens[i][0]))
{
stack_push(strtol(token, NULL, 10));
}
else if(strcmp(tokens[i], "sin") == 0)
{
stack_push(sin(stack_pop()));
}
else if ...
}
請注意,這非常粗糙,僅旨在概述如何解決此問題。
你有兩個問題。 一:
我如何從文件中讀取sin,log等
另一個:
我如何...將它們放入數組
第一個問題:從文件中讀取。 使用strtok
將一行文本分隔為“單詞”。 使用strcmp
檢查函數名稱。
int main(){
char str[] = "2 3 +";
char *p;
for (p = strtok(str, " "); p != NULL; p = strtok(NULL, " ")) {
if (isdigit(*p)) { // it's a number
long val = strtol(p, &p, 10);
printf("%ld\n", val);
} else { // it's a name of a function
if (strcmp(p, "+") == 0)
puts("Add");
else if (strcmp(p, "-") == 0)
puts("Subtract");
else if (strcmp(p, "sin") == 0)
puts("Sine");
else if (strcmp(p, "log") == 0)
puts("Logarithm");
else if ...
...
else
fputs("Error!", stderr);
}
}
}
第二個問題:添加到數組中。 我建議使用標記的聯合 :
enum type {CONSTANT, UNARY_FUNCTION, BINARY_FUNCTION, X};
struct operation
{
enum type type;
union {
double val;
double (*func1)(double); // a pointer to a function with 1 argument
double (*func2)(double, double); // a pointer to a function with 2 arguments
};
};
此處,“運算”有4種可能的類型-它可以是數字,一元函數(如sin
),二進制函數(如+
)或自變量x
。
要將令牌p
轉換為operation
:
char *p;
struct operation o;
...
if (isdigit(*p)) { // it's a number
o.type = CONSTANT;
o.val = strtol(p, &p, 10);
} else { // it's a name of a function or "x"
if (strcmp(p, "x") == 0)
{
o.type = X;
}
else if (strcmp(p, "+") == 0)
{
o.type = BINARY_FUNCTION;
o.func2 = plus;
}
else if (strcmp(p, "sin") == 0)
{
o.type = UNARY_FUNCTION;
o.func1 = sin;
}
else if (strcmp(p, "log") == 0)
{
o.type = UNARY_FUNCTION;
o.func1 = log;
}
...
}
在此函數plus
兩個數字。 標准庫沒有它(不像sin
那樣),所以我必須自己定義它:
double plus(double x, double y) {return x + y;}
最后,如果您有一組operation
對象:
struct operation my_array[1000];
您可以將對象添加到數組:
struct operation my_array[1000];
size_t my_array_size = 0;
for (...)
{
... // parse input file
struct operation o;
... // parse individual token and convert it to an "operation"
my_array[my_array_size++] = o; // add to the array
}
該程序的主要部分是使用數組為x
任何值計算編碼函數的值。 現在,您已將函數編碼為一系列操作,計算本身將很容易。 只需臨時堆放值,然后應用每個操作即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.