<ma******@gmail.com> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
i have a quick question
i am putting a debug flag in my program (i really dont need this
feature, but i figured it might be useful when i get into trouble)
so i want to check if argv[2] is the letter "d"
this is what i have so far
if (argv[2]) { write_read_input_file(filename); }
(it works, as long as there's more than 1 argument to the program, it
works. good enough for a lousy flag which i don't need, but i am not
satisfied)
i tried doing the following
argv[2] == "d" //compiles, but doesn't work
argv[2] == 'd' //can't do this
strcmp(argv[2], "d") //segmentation fault
God I wish c++ was like perl. :-)
argv[2] should be a char*. That is, it points somewhere in memory.
argv[2] == "d" wouldn't work, because you are comparing wehre argv[2] is
pointing at to where the constant char array "d" is stored, which are of
course different.
Same as for argv[2] == 'd' although now you're comparing a pointer to a
character (integer value).
strcmp(argv[2], "d") should work.
I think you are confused though. The second parameter is argv[1], not
argv[2], since arrays in c++ are 0 based. This works for me with the
comamnd line parmaters passed: "xxxx d"
#include<iostream>
int main(int argc, char* argv[])
{
std::cout << "Arguments: " << argc << std::endl;
std::cout << "Arg 0:" << argv[0] << std::endl;
if ( argc > 1 )
std::cout << "Arg 1:" << argv[1] << std::endl;
if ( argc > 2 )
{
std::cout << "Arg 2:" << argv[2] << std::endl;
std::cout << "Art 2 is \"d\":" << strcmp(argv[2], "d") << std::endl;
}
return 0;
}
Output is:
C:\temp\console\Debug>console xxx d
Arguments: 3
Arg 0:console
Arg 1:xxx
Arg 2:d
Art 2 is "d":0
Notice: Different OSes may pass the first argument (argument 0) as the
executable name used to execute the program. This may also include the
path.
Notice: strcmp() returns 0 if they are equal.
HTH