【问题标题】:What does argc mean? [duplicate]argc 是什么意思? [复制]
【发布时间】:2016-07-04 22:52:44
【问题描述】:

我不明白,OpenCV 中加载图像的代码的功能是什么。 if(argc !=2) 的作用是什么?你能告诉我吗?

 if( argc != 2)
    {
     cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
     return -1;
    }

完整代码:

1 #include <opencv2/core/core.hpp>
2 #include <opencv2/highgui/highgui.hpp>
3 #include <iostream>
4
5 using namespace cv;
6 using namespace std;
7
8 int main( int argc, char** argv )
9 {
10 if( argc != 2)
11 {
12 cout <<" Usage: display_image ImageToLoadAndDisplay" << endl;
13 return -1;
14 }
15
16 Mat image;
17 image = imread(argv[1], CV_LOAD_IMAGE_COLOR); // Read the file
18
19 if(! image.data ) // Check for invalid input
20 {
21 cout << "Could not open or find the image" << std::endl ;
22 return -1;
23 }
24
25 namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
26 imshow( "Display window", image ); // Show our image inside it.
27
28 waitKey(0); // Wait for a keystroke in the window
29 return 0;
30 }

【问题讨论】:

  • 请不要发布带有行号的代码。

标签: c++


【解决方案1】:

这应该在任何 C++(或 C、ObjC 或相关语言)教程中涵盖,例如 the GNU tutorial

C++ 程序的main 函数有两个参数,按照约定命名为argcargv,它们为其提供了用于启动程序的命令行参数。

argc 是参数个数,argv 是字符串数组。

程序本身是第一个参数argv[0],所以argc总是至少为1。

所以,当程序使用一个命令行参数运行时,argc2。如果运行时不带参数或多个参数,argc != 2 将为真,因此将打印用法消息“Usage: display_image ImageToLoadAndDisplay”,告诉用户如何正确运行它。


例如,如果你这样做:

$ display_image firstarg "second arg"

值将是:

argc: 3
argv[0]: "display_image"
argv[1]: "firstarg"
argv[2]: "second arg"

可能值得指出的是,代码在很多方面都很奇怪。使用信息开头的多余空格很奇怪。 “用法”通常全部小写。您通常将实际程序名称 (argv[0]) 放在字符串中,而不是硬编码的规范名称。使用消息通常发送到cerr,而不是cout。约定是为用户错误返回一个正数,通常为 2 表示无效参数,而不是 -1。您可以在源代码中找到更好的argc/argv 处理示例,用于处理几乎所有在 Unix 命令行上使用的工具(尽管它们中的大多数都更复杂,通常使用像 getopt 这样的库来解析来自文件参数的选项等)。

【讨论】:

  • 非常感谢。现在我明白了。我是 OpenCV 的新手。
  • @Dejan:这与 OpenCV 无关;它是 C++(和 C)的基本特征。
【解决方案2】:
  • argc = 参数计数。这用于确定数量 运行程序的命令行参数。
  • argv 被称为参数向量,它包含所有命令行参数的名称,包括您的程序名称。
  • 在您运行的任何程序上,argc 始终至少为 1;这是因为 程序本身包含在争论计数中。所以在 您的程序,argc 必须为 2,其中包括: your_programanother_file。如果 argc 不是 2,这意味着它是 等于 1 或大于 2,因为这不是 程序需要,代码中止进一步执行

【讨论】:

  • 感谢您的回复。现在我明白了。
猜你喜欢
  • 2022-06-20
  • 2011-03-02
  • 1970-01-01
  • 2019-09-12
  • 2015-01-22
  • 2020-10-27
  • 2015-07-15
相关资源
最近更新 更多