处理命令行参数
我一直在使用 OpenCV,我见过的一些示例代码使用以下内容来读取文件名。我知道 argc 是传递的命令行参数的数量,argv 是参数字符串的向量,但是有人可以澄清以下行的每个部分的作用吗?我尝试过搜索此内容,但没有找到很多结果。谢谢。
const char* imagename = argc > 1 ? argv[1] : "lena.jpg";
谢谢。
I've been working with OpenCV, and some of the example code I've seen uses the following to read in a filename. I understand that argc is the number of command line arguments that were passes, and argv is a vector of argument strings, but can someone clarify what each part of the following line does? I've tried searching this but haven't found many results. Thanks.
const char* imagename = argc > 1 ? argv[1] : "lena.jpg";
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果 argc 大于 1,则将 argv[1] 中保存的指针(即命令行上给出的第一个参数)分配给 imagename;否则(argc 不大于 1),分配默认值“lena.jpg”。
它使用三元运算符
?:
。这是这样使用的:CONDITION ? A : B
可以读作So that
a = C ? A : B
如果C
为 true,则将 A 分配给a
,否则将B
分配给a
。在本例中,“A”和“B”是指向char
(char *
) 的指针; const 属性表示我们有“常量”的“字符串”。If argc is greater than 1, assigns to imagename the pointer held in
argv[1]
(i.e. the first argument given on the command line); otherwise (argc is not greater than 1), assigns a default value, "lena.jpg".It uses the ternary operator
?:
. This is used this way:CONDITION ? A : B
and can be read asSo that
a = C ? A : B
assigns A toa
ifC
is true, otherwise assignsB
toa
. In this specific case, "A" and "B" are pointers tochar
(char *
); theconst
attribute says we have "strings" that are "constant".该示例显示了三元运算符的使用。
const char* imagename = argc >; 1 : argv[1] : "lana.jpg"
通过三元,您可以说该表达式具有三个成员。
第一个成员是条件表达式
第二个成员是如果条件表达式为真则可以分配给 imagename 的值。
第三个成员是如果条件表达式为 false 时可以分配给 imagename 的值。
这个例子可以翻译为:
The example shows the use of the ternary operator.
const char* imagename = argc > 1 : argv[1] : "lana.jpg"
By ternary you can say that this expression has three members.
First member is a condition expression
Second member is the value that could be assigned to imagename if conditional expression is true.
Third member is the value that could be assigned to imagename if conditional expression is false.
This example can be translated to:
(如果我们同意
imagename
可以超出括号的范围)(if we agree that
imagename
can go out of the brackets' scope)