-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?!

1
  • You should use << std::endl after writing your output, to guarantee flushing of std::cout BTW. Commented Aug 19, 2013 at 18:53

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

4 Comments

@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
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).
@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 stackoverflow.com/q/16418932/311966 for details
@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).
5
if (_tcscmp(argv[1], _T("arg1")) == 0) {
    cout << "Argument1 was passed" << endl;
}

2 Comments

+1. I'd missed the use of _TCHAR
@simonc yes, but you was first ;)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.