如何获取程序调用的第一个参数
我正在用 C 语言编写一个程序,这是我的代码:
int main(int argc, char **argv) {
int n;
char aux[10];
sscanf(argv[1], "%[^-]", aux);
n = atoi(aux);
}
因此,如果我从命令行运行该程序: my_program -23,我想获得数字“23”以将其隔离在像整数一样的 var 中,但是这个不起作用,我不知道为什么......
I'm making a program in C and this is my code:
int main(int argc, char **argv) {
int n;
char aux[10];
sscanf(argv[1], "%[^-]", aux);
n = atoi(aux);
}
So, if I run the program from command line: my_program -23, I want to get the number "23" to isolate it in a var like an integer, but this don't work and I don't know why...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 sscanf 调用尝试读取字符串中第一个
-
之前(但不包括)的任何内容。由于-
(大概)是第一个字符,因此aux
最终为空。您可以执行以下操作:
sscanf(argv[1], "%*[-]%d", &n);
。这将跳过任何前导-
字符,因此23
、-23
和--23
的参数都将予以同等对待。如果您希望将--23
解释为-23
(只有一个前导破折号表示标志),那么您可以使用sscanf(argv[1] , "-%d", &n);
(在这种情况下,如果命令行上只有23
,转换将彻底失败)。Your
sscanf
call is trying to read anything up to (but not including) the first-
in the string. Since the-
is (presumably) the first character, itaux
ends up empty.You could do something like:
sscanf(argv[1], "%*[-]%d", &n);
. This will skip across any leading-
characters, so arguments of23
,-23
and--23
will all be treated identically. If you want--23
to be interpreted as-23
(only the one leading dash signals a flag), then you could usesscanf(argv[1], "-%d", &n);
(and in this case, with just23
on the command line, the conversion will fail outright).检查你的 sscanf 格式,我假设 aux 是一个整数?
来自 http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/< /a>
sscanf(str,"%d",&n);
check your sscanf format, and I assume aux is an integer?
from http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/
sscanf (str,"%d",&n);