I am wondering how I can compare the command line arguments with predefined strings/char arrays.
1 2 3 4 5 6 7 8 9 10 11
int main(int argc, char *argv[])
{
if(argv[1] == 'hello') // error since 'hello' is a char array and argv[1] is a pointer
cout << "hello" << endl;
char param = argv[1];
if(param == 'hello') // error since 'hello' is a char array and param is not.
cout << "hello" << endl;
return 0;
}
You code doesn't work because you are using single quotes around your strings. These are usually used to enclose single characters (as far as I know).
You want to use double quotes( "Your String" ). Also I'm pretty sure that direct comparison between character strings ( char* == char* ) is not possible. I found this explanation on the stackoverflow forums:
stackoverflow wrote:
Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ.
as it is testing the address of the argument string (as in, pointer to a null terminated string) against the address of a constant string. Even if the value of argv[1] is "hello", the condition will fail as the two "hello"s are stored at different memory addresses, and the pointer values therefore differ.
(in a belated - failed? - attempt to re-clarify an earlier comment.)
Andy
P.S. I have just today bumped into some open source making exactly this mistake! As I habitually crank the warning up level to max, the bad code was immediately flagged. But it seems to be a pretty common mistake to make!
Once again, to clearify further, 'hello' is invalid syntax and should never compile according to the standard. Character literals are exactly one character--never more and never less. ('\n' is consider a single character.)