I have asked a similar question about command line arguments in C++ some hours ago. Now I have another problem, as far as I know, command line arguments will be saved like a string in argv array. so comparing theme with a string should be logical, but it does not work in the way I want, look at this code:
#include <iostream>
using namespace std;
int main(int argc,char** argv)
{
if (argv[2]=="stack") cout << "right";
cout << argv[2];
return 0;
}
now I pass this command to my compiled application named zero.exe;
zero.exe stack
the output should be "rightstack", but if
command will skip and only cout << argv[2];
will execute, so only stack will be shown on monitor. it shows "stack"
is saved into argv[2]
, so if (argv[2]=="stack")
should work, but it is not. where is the problem?
For historical reasons, the arguments are passed as C-style strings; that is, each is a pointer to an array of characters, with a zero-valued character to mark the end. Similarly, a string literal (like "stack"
) is a simple array of characters.
Your code compares two pointers, which will not be equal even if the string values are equal. To compare the strings, either convert one (or both) to std::string
:
#include <string>
std::string arg2(argv[2]);
if (arg2=="stack") std::cout << "right\n";
or use the C library function for comparing C-style strings; this might be more efficient, but is also harder to read:
#include <cstring>
if (std::strcmp(argv[2], "stack") == 0) std::cout << "right\n";
Also, the arguments are counted from 1, with the program name as argv[0]
, so you probably want to be testing argv[1]
rather than argv[2]
.
The problem is that argv[2]
is a different "stack" than the string literal "stack" you have in your program.
This is C++ after all, where if you compare two strings the way you did, you're only comparing their addresses.
Edit:
In your example, zero.exe stack
, argv[0]
contains the program name and argv[1]
contains the "stack", so you're also off by one.
More edit:
I think I see where the numbering confusion comes from... If you're running under the Visual Studio debugger, you can enter command line parameters in the project's property pages, and in that case, the zero.exe
would become argv[1], yes. The name of the program itself will always be in argv[0].