Using argv in C?
Asked Answered
C

6

10

For an assignment, I am required to have command line arguments for my C program. I've used argc/argv before (in C++) without trouble, but I'm unsure if C style strings are affecting how this works. Here is the start of my main:

int main(int argc, char *argv[]){

  if(argc>1){
    printf("0 is %s, 1 is %s\n",argv[0],argv[1]);
    if(argv[1]=="-e"){
        // Do some stuff with argv[2]
        system("PAUSE");
    }
    else{
        printf("Error: Incorrect usage - first argument must be -e");
        return 0;
    }
  }

So I am calling my program as "program.exe -e myargstuff" but I am getting the "Error: Incorrect Usage..." output, even though my printf() tells me that argv[1] is "-e". Some help, please? Thanks!

Cavil answered 20/2, 2010 at 2:7 Comment(0)
I
18

The line

if(argv[1]=="-e"){

compares pointers, not strings. Use the strcmp function instead:

if(strcmp(argv[1],"-e")==0){
Infarct answered 20/2, 2010 at 2:9 Comment(2)
Haha. 6 answers just like mine in the time it took me to write the answer.Kopaz
Well, that absolutely did it. Thank you for correcting this, I'm very new to C!Cavil
E
7

Change:

if(argv[1]=="-e"){

to

if(strcmp(argv[1], "-e") == 0){

and include string.h.

Elocution answered 20/2, 2010 at 2:10 Comment(0)
A
5

Check out getopt() and related functions; it'll make your life a lot easier.

Anthesis answered 20/2, 2010 at 2:10 Comment(0)
L
3

You can't compare c-strings like that. Use strcmp (reference here).

Because c-strings are actually pointers, the == operator compares the address of the first character which will never be equal in this case.

Lixiviate answered 20/2, 2010 at 2:10 Comment(0)
I
2

You can't use == to compare strings like that in C. That's just comparing the addresses of argv[1] and your literal, which are pretty much guaranteed to be different.

Use strcmp instead. eg:

if (!strcmp("-e", argv[1])) {
Irs answered 20/2, 2010 at 2:10 Comment(0)
B
1

The prototype of the main function says you're dealing with char* pointers. In C, there is no operator overloading; therefore, == between two char* will test if they point to the same place. This is not the case, and is rarely the case at all. Use the strcmp (the reference for the function is valid even though it points to a C++ site) function from <string.h>:

strcmp(argv[1], "-e") == 0
Bendicta answered 20/2, 2010 at 2:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.