LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Command Line Options in C++ (https://www.linuxquestions.org/questions/programming-9/command-line-options-in-c-48801/)

crichards 03-07-2003 10:42 PM

Command Line Options in C++
 
I'm trying to learn how to add command line options to a C++ program, and here's what I have (not the entire program, just the relevant parts):

Code:

int main(int argc, char **argv) {
        if (argv[1] == "c")
                std::cout << "Argument 'c'\n";
        else
                std::cout << "No argument\n";
}

I'm wondering why, when I compile it, it doesn't output "Argument 'c'" when I give argv[1] as c (run as ./args c)...

Driving me insane...

Dark_Helmet 03-07-2003 11:29 PM

I'm familiar with C, not C++, so this may not apply. I'm going to pretend it's C code though... :)

The problem is your comparison:
Code:

if (argv[1] == "c")
In essence, you're comapring pointers/addresses and NOT the contents of the string. In C, you'd use the strcmp() function. It would return 0 if the two strings are equal.

Now, I know C++ is fond of function/operator overloading. So the equality test might be mapped to a string comparison function already. However, I doubt that since everything else seems to be ok.

As a side note, you should always check argc before referencing any string arguments. If you reference argv[1] and there were no arguments given, at best, you'll get a segfault. At worst, you'll get garbage that might affect how the program runs. I know, I know, this is just a test program... Just wanted to point that out though...

crichards 03-08-2003 12:56 PM

OK, I got it to work by using the std::strcmp function, but is there any better C++ alternative? Its in the cstring header, and I can't find an equivalent function in the C++ string header...

Dark_Helmet 03-08-2003 01:01 PM

You've got me there... I don't know a lot of the standard C++ functions supplied simply because I don't program in it very often. Maybe somebody else watching this thread will know...

Yeah YOU! We know you're out there!

sienarot 03-08-2003 03:29 PM

Is this what you're looking for?

#include<iostream.h>
#include<string.h>

int main(int argc, char *argv[])
{
if(!strcmp(argv[1], "c"))
cout << "Argument 'c'\n";
else
cout << "No argument\n";

return 0;
}

sienarot 03-08-2003 03:42 PM

< oops, double post :) >


All times are GMT -5. The time now is 01:24 AM.