Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking argv[] against a string? (C++)

Tags:

c++

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.

like image 534
Ben Avatar asked Mar 03 '11 16:03

Ben


People also ask

What does * argv [] mean?

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.

Is argv a string?

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.

Is argv 1 a string?

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.


1 Answers

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       }   }  } 
like image 154
Erik Avatar answered Sep 24 '22 05:09

Erik