I have following program and i am passing it 2 arguments at the command line as shown below. I was expecting the argc to be 3, but it prints it as 6. why?
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
void usage();
int main(int argc, char *argv[])
{
cout << argc << endl;
if (argc != 3)
usage();
string regex = argv[1];
string searchString = argv[2];
cout << "regex: " << regex << " . searchString: " << searchString << endl;
return 0;
}
void usage()
{
cout << "Usage: ./stringmatch <regex> <searchString>" << endl;
exit(1);
}
Command line:
[jim@cola c++]$ ./stringmatch [yyyy\d\d\d]* yyyy1234
6
Usage: ./stringmatch <regex> <searchString>
Your shell is expanding the glob pattern [yyyy\d\d\d]*
so the actual number of arguments this results in depends on the contents of the current directory!
The [yyyy\d\d\d]
becomes a character class matching the characters y
and d
, and the *
matches anything that follows, so I'm guessing your current directory has 4 files that start with y
or d
. To see what it expands to, use echo
:
$ echo [yyyy\d\d\d]*
To make it work as intended, quote the argument:
$ ./stringmatch '[yyyy\d\d\d]*' yyyy1234