-3

I am trying to parse the run-arguments within my console application with this code:

int _tmain(int argc, _TCHAR* argv[])
{
    if(argv[1] == _T("arg1")) cout<<"Argument1 was passed";
    _getch();
    return 0;

}

My code doesn't work. I mean, it runs, but the console is empty. I am compiling with Use Unicode Character Set option in Visual Studio 2012 (on Windows 7). Where is my mistake?!

Victor
  • 13,914
  • 19
  • 78
  • 147

3 Answers3

8

Use strcmp to compare char arrays

if(strcmp(argv[1], "arg1") == 0)

Use of == just compares pointers to two different strings.

See Darius Kucinskas' answer for comparing _TCHAR arrays

simonc
  • 41,632
  • 12
  • 85
  • 103
  • @Victor I've updated to show how to compare `argv[1]` to an ascii string. Darius Kucinskas' answer points to the equivalent function for `_TCHAR` – simonc Aug 19 '13 at 18:50
  • This works, as long as he actually passes something in on the command line. If he just runs the program (with no command line arguments), behavior is undefined (he is attempting to access passed the end of the array). – Zac Howland Aug 19 '13 at 19:00
  • @ZacHowland I don't think behaviour is undefined for quite that reason. I agree that checking for `argc>1` is necessary but accessing `argv[argc]` is well defined - to return `NULL`. See http://stackoverflow.com/q/16418932/311966 for details – simonc Aug 19 '13 at 19:21
  • @simonc: True (Section 3.6.2 states as much), but it is still VERY bad practice to attempt to access outside the range of an array. And in this case, if he continues to pass nothing on the command line, he will be calling `strcmp(NULL, "arg1") == 0` every time, which will always be false (and result in the console still being empty). – Zac Howland Aug 19 '13 at 19:28
5
if (_tcscmp(argv[1], _T("arg1")) == 0) {
    cout << "Argument1 was passed" << endl;
}
Darius Kucinskas
  • 10,193
  • 12
  • 57
  • 79
0

You have a few mistakes:

1) You cannot compare C-style strings (character arrays) using the == operator. argv[#] is a character array, as is _T("some value"). In order to compare them, you need to use strcmp (or one of it's cousins), or store it in a std::string.

2) You are attempting to access the 2nd element of the array, but only 1 element exists. you said you were passing nothing to the call, meaning argv[0] will contain data (the name of the executable you are running), but argv[1] will not. In general, attempting to access it will be attempting to access data outside the range of the array with undefined results. In this particular case, the standard (Section 3.6.2) states that it will always be 0 (aka NULL). So your conditional will always be false.

3) You should ALWAYS check the value of argc when command line parameters are expected.

Zac Howland
  • 15,777
  • 1
  • 26
  • 42