-4

I'm trying to use main() parameter vectors to get three options, it output all three results. why cannot it work?

#include <ctype.h>
#include <stdio.h>
void output_1(char *str);
void output_2(char *str);
void output_3(char *str);
int main(int argc,char *argv[])
{
    char str[40];

    gets(str);
    
    if (argv[1]="-p")
    {
        output_1(str);
    }
    if (argv[1]="-u")
    {
        output_2(str);
    }
     if (argv[1]="-l")
    {
        output_3(str);
    }
}

the definations of output_1/2/3 don't matter.

hiljq
  • 1
  • 2
    You compare null-terminated byte strings using `strcmp` not `==` – UnholySheep Oct 08 '20 at 08:13
  • 3
    Also your code uses assignment `=` instead of comparisons – UnholySheep Oct 08 '20 at 08:14
  • 1
    The other comments correctly identify the problem with the given code, but worth also mentioning that parsing command line arguments is best performed by using getopt. – racraman Oct 08 '20 at 08:18
  • 1
    Just to complete the review: [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/q/1694036/11336762) – Roberto Caboni Oct 08 '20 at 08:22
  • 1
    @RobertoCaboni Please do not give the impression to new users that they get code reviews here. The idea of StackOverflow is to answer specific questions. (Your comment is otherwise of course wise.) – Yunnosch Oct 08 '20 at 08:24
  • Appreciate your answers, it is useful to me – hiljq Oct 08 '20 at 11:33

1 Answers1

1

C string comparison uses strcmp.
Here is a code sample on how to test command line arguments and ensure the parsing is robust (number of arguments need to be checked). However parsing argument is best done using getopt functionality.

#include <stdio.h>
#include <string.h>
int main(int argc,char *argv[])
{

    if (argc != 2)
    {
        printf("missing arguments");
        return -1;
    }   
    if (!strcmp(argv[1],"-p"))
    {
       printf("-p");
    }
    else
    {
         printf("unknwon arg %s",argv[1]);
    }
}
Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39
Jean-Marc Volle
  • 3,113
  • 1
  • 16
  • 20
  • @Yunnosch. The OP error is so obvious that it is good to explain how to compare strings in C and ensure the code will not crash in case arg count is not the expected. Then sure `getopt` is the way forward for if the question was about how to parse command line arguments – Jean-Marc Volle Oct 08 '20 at 08:30