我想使用atof()將字符串轉換爲double(顯然),但結果不是我所期望的。這裏是關於變量值的代碼和調試信息之前ATOF():atof創建奇怪的結果
d = atof (arg);
next.db = d;
*debug info*
arg = 0x0034f7b0 "10.0"
d = 0.0000000000000000
一旦程序通過ATOF臺階()。結果如下:
arg = 0x0034f7b0 "ôþSÄ÷4"
d = 0.0000000000000000
正如你所看到的,命令前,ARG變量並持有有效的兩倍。儘管如此,返回值是0.令我困惑的是,爲什麼arg的值會發生變化?
另外,我確實包含了stdlib.h。如果有幫助可言,「10.0」從文件中讀取
char *arg;
:同樣,arg被聲明爲。
更多代碼:
void read_instructions()
{
char *str;
char *arg;
int n;
char c;
double d = 0;
instruction next = {0};
while (!feof(datafile)) {
// Fetch the next string
// if (push or pop), get the next argument
// create instructiwn and add to instruction array
str = get_next_string();
if (strncmp (str, "P", 1) == 0) {
if (strncmp (str, "PUSH", 4) == 0) {
next.func = pushFunc;
}
else {
next.func = popFunc;
}
arg = get_next_string();
n = arg[0];
if (n > 64 && n < 71)
next.ch = arg[0];
else {
d = atof (arg);
next.db = d;
}
instr[instr_count] = next;
instr_count++;
}
else {
c = str[0];
switch (c) {
case 'A' :
next.func = addFunc;
break;
case 'S' :
next.func = subFunc;
break;
case 'M' :
next.func = multFunc;
break;
case 'D' :
next.func = divFunc;
break;
case 'H' :
next.func = haltFunc;
default :
printf ("Invalid instruction");
}
instr[instr_count] = next;
instr_count++;
}
}
fclose (datafile);
}
這是給定的代碼來打開和訪問文件:
FILE *datafile;
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("error, incorrect number of arguments");
haltFunc(instr[0]);
}
open_file(argv[1]);
read_instructions();
execute_instructions();
return 0;
}
void open_file(char* argv)
{
char buf[1024];
char cwd[512];
getcwd(cwd, sizeof cwd);
sprintf(buf, "%s\\%s", cwd, argv);
if (!(datafile = fopen(buf, "r"))) {
printf("Error: Make sure your file is located here:\n%s", buf);
}
}
char* get_next_string()
{
char str[15];
fscanf(datafile, "%s", &str);
return str;
}
頭文件:
#ifndef MAIN_HEADER_H
#define MAIN_HEADER_H
#define INSTR_SIZE 30
typedef struct {
void (*func)(instruction);
union {
double db;
char ch;
};
} instruction;
int main(int, char*);
char* get_next_string();
void open_file(char*);
void read_instructions();
void execute_instructions();
void pushFunc(instruction instr);
void popFunc(instruction instr);
void addFunc(instruction instr);
void subFunc(instruction instr);
void multFunc(instruction instr);
void divFunc(instruction instr);
void haltFunc(instruction instr);
#endif
這是測試文件:
PUSH 10.0
PUSH 4.0
PUSH 7.0
PUSH 5.0
POP D
POP E
POP
PUSH D
ADD
PUSH 5.0
POP B
PUSH 17.0
POP E
PUSH B
PUSH E
SUB
HALT
你能顯示整個代碼嗎?你可能會改寫那裏的東西。 – nhahtdh 2012-07-11 02:50:31
重寫什麼?唯一涉及的是變量和函數調用。 – Troncoso 2012-07-11 03:06:25
我不確定。您顯示的代碼似乎沒有任何問題。給我們一些我們可以重現效果的代碼。 – nhahtdh 2012-07-11 03:10:00