So I'm attempting to check the arguments that I'm inputting into my program, and one of them is either the word "yes" or "no", entered without the quotes.
I'm trying to test equivalency ( if (argv[n] == "yes") ) but that seems to be returning false every time when the input is, in fact, yes(When I output it it confirms this). What am I missing here that I'm doing improperly? If I understand properly argv[n] returns a cstring that is null-terminated, so it should allow me to do this.
As a concept, ARGV is a convention in programming that goes back (at least) to the C language. It refers to the “argument vector,” which is basically a variable that contains the arguments passed to a program through the command line.
The second argument to main, usually called argv, is an array of strings. A string is just an array of characters, so argv is an array of arrays. There are standard C functions that manipulate strings, so it's not too important to understand the details of argv, as long as you see a few examples of using it.
Argc and argv Argv looks weird, but what it is is an array of C-style strings. Sometimes you see it declared as "char *argv[]," which is equivalent to the above. Element argv[i] will be a c style string containing the i-th command line argument. These are defined from 0 through argc-1.
You're comparing pointers. Use strcmp, or std::string.
int main(int argc, char * argv[]) { if (argv[1] == "yes"); // Wrong, compares two pointers if (strcmp(argv[1], "yes") == 0); // This compares what the pointers point to if (std::string(argv[1]) == "yes"); // Works fine if (argv[1] == std::string("yes")); // Works fine // Easy-mode std::vector<std::string> args(argv, argv+argc); for (size_t i = 1; i < args.size(); ++i) { if (args[i] == "yes") { // do something } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With