c++ - What does argc mean? -
this question has answer here:
- opencv argc , argv confusion 1 answer
i can't understand, whats function of code in opencv loading image. whats function of if(argc !=2)? can tell me it.
if( argc != 2) { cout <<" usage: display_image imagetoloadanddisplay" << endl; return -1; }
full code:
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 file 18 19 if(! image.data ) // check invalid input 20 { 21 cout << "could not open or find image" << std::endl ; 22 return -1; 23 } 24 25 namedwindow( "display window", cv_window_autosize );// create window display. 26 imshow( "display window", image ); // show our image inside it. 27 28 waitkey(0); // wait keystroke in window 29 return 0; 30 }
this should covered in tutorial c++ (or c, objc, or related languages), such the gnu tutorial.
the main
function of c++ program has 2 parameters, convention named argc
, argv
, give command-line arguments used launch program.
argc
count of arguments, , argv
array of strings.
the program first argument, argv[0]
, argc
@ least 1.
so, argc
2
when program run 1 command-line argument. if it's run no arguments, or more one, argc != 2
true, usage message " usage: display_image imagetoloadanddisplay" printed, telling user how run properly.
for example, if this:
$ display_image firstarg "second arg"
the values be:
argc: 3 argv[0]: "display_image" argv[1]: "firstarg" argv[2]: "second arg"
it may worth pointing out code weird in many ways. space @ beginning of usage message weird. "usage" in lowercase. typically put actual program name (argv[0]
) in string rather hardcoded canonical name. usage messages go cerr
, not cout
. , convention return positive number errors user's fault, typically 2 invalid arguments, not -1. can find better examples of argc
/argv
handling in source code tool made used on unix command line (although of them more complicated, using libraries getopt
parse out options file arguments, etc.).
Comments
Post a Comment