-3

I am learning C, and I am in the part about the arguments: int argc, char *argv[].

I am trying to make a code that prints a result according to the argument put in console. For example:

./a.out -E
to print "Hello World!"

./a.out -S
to print "Hello World in Spanish"

I have the following code, but I still don't know how to get it.

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

    if(argc == 1){
        printf("Hello World!");
    }
    else if(argc > 2){
        printf("Too many arguments supplied.\n");
    }
    else if(argv[2] == '-S'){
        printf("Hola Mundo in Spanish"); //show errors
    }
    else {
        printf("Hello, %s!!\n", argv[1]);
    }
    return EXIT_SUCCESS;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • What do you mean by "how to get it"? What happened when you tried to run the program? How is that different from what is supposed to happen? Does it work correctly with some command lines, and not with others? – Karl Knechtel Oct 08 '20 at 23:56
  • 1
    `argv[2] == '-S'` is virtually certain to always be false, regardless of program arguments. See [How do I properly compare strings in C](https://stackoverflow.com/questions/8004237/how-do-i-properly-compare-strings-in-c). And note, too, that `'-S'` is not a string (but `"-S"` is). – John Bollinger Oct 08 '20 at 23:59

1 Answers1

2

Array indexing in C is zero-based. If argc is 2, then argv[0] is the path to your executable, and argv[1] is the first argument.

The other problem you have is you cannot compare char* strings with ==, and you cannot have a single character '-S'. Yes, single-quotes is for a character, and double-quotes is for a string.

Use strcmp() from <string.h> as follows:

if (strcmp(argv[1], "-S") == 0) {
    printf("Hola Mundo in Spanish\n");
}
paddy
  • 60,864
  • 6
  • 61
  • 103
  • 2
    `'-S'` is a multi-byte character constant, whose value is implementation defined. Because in C, character constants have type `int`, some compilers have extensions in this area. In GNU C, you can have a constant like `'ABCD'` which will pack those characters value into a 32 bit `int` value. Not sure what (actually, don't care what) happens in GNU C++, since in C++, character constants have type `char`. – Kaz Oct 09 '20 at 00:12
  • 1
    Thanks for the extra information. If it's not specifically in the language standard, I'm more comfortable just saying you can't do it (and be technically wrong), than I am to overwhelm a beginner with specifics :) – paddy Oct 09 '20 at 00:17
  • If argc is 2, argv[2] is guaranteed to be a null pointer. argv[3] is undefined behaviour. (5.1.2.2.1/2: "argv[argc] shall be a null pointer.") – rici Oct 09 '20 at 00:24
  • I have removed that claim from my answer. :) – paddy Oct 09 '20 at 00:27
  • Multi-character constants are explicitly allowed by the standard (C11 [§6.4.4.4 Character constants ¶10](http://port70.net/~nsz/c/c11/n1570.html#6.4.4.4p10)), but the value is implementation-defined. – Jonathan Leffler Oct 09 '20 at 06:08