[英]Why do I get a floating point exception?
While trying to take some arguments for C. I found it really difficult to get argv[]
to work.在尝试为 C 取一些 arguments 时。我发现很难让
argv[]
工作。 I have:我有:
int main(int argc, char *argv[])
{
void updateNext();
void fcfs();
void spn();
void srt();
fp = fopen(argv[0],"r");
op = fopen("output.dat","a+");
if (strcmp(argv[1],"FCFS")!=0)
{
fcfs();
}
if (strcmp(argv[1],"SPN")!=0)
{
spn();
}
if (strcmp(argv[1],"SRT")!=0)
{
srt();
}
}
I would like to enter something in a format of myprog input.data FCFS
, but the above code gives me an error for "float point exception" the exception is gone after I hard code input.dat
as a string in the program.我想以
myprog input.data FCFS
的格式输入一些内容,但上面的代码给我一个“浮点异常”的错误,在我input.dat
硬编码为程序中的字符串后,异常消失了。 Something wrong with argv[0]
perhaps? argv[0]
有问题吗?
In C, argv[0]
is the name of your program (or more precisely, the first word the user typed on the command line to run your program, if run from a shell).在 C 中,
argv[0]
是您的程序的名称(或者更准确地说,如果是从 shell 运行,则用户在命令行上键入的第一个单词来运行您的程序)。
So, avoiding argv[0]
for your purposes, you'll want to look at argv[1]
for the file name and argv[2]
for the other parameter.因此,为了您的目的避免使用
argv[0]
,您需要查看文件名的 argv[ argv[1]
和其他参数的argv[2]
。
This would have been clear if you had used a debugger to trace through your program, or simply printed the value before you used it:如果您使用调试器跟踪您的程序,或者只是在使用它之前打印该值,这将很清楚:
printf("using file name %s\n", argv[0]);
fp = fopen(argv[0],"r");
It's also a good idea to check that you have sufficient command line parameters by validating argc
before accessing argv
:在访问
argv
之前通过验证argc
来检查您是否有足够的命令行参数也是一个好主意:
if (argc < 3) {
fprintf(stderr, "not enough command line parameters\n");
exit(1);
}
In C argv[0]
is typically the name with which the program was called.在 C 中,
argv[0]
通常是调用程序的名称。 You're looking for argv[1]
and argv[2]
.您正在寻找
argv[1]
和argv[2]
。
As side notes:作为旁注:
argc
before touching argv
argv
之前检查argc
argv[0]
contains the name of the program or even something sensibleargv[0]
包含程序名称或什至是合理的名称
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.