Shirin Abedi
Shirin Abedi

Reputation: 13

optional command line arguments for client program in c++

I have to modify this code which needs 2 command line argument

  if (argc == 3){
   host = argv[1];
    port = atoi(argv[2]);
      else {
    fprintf(stderr, "usage error: incorrect number of arguments\n");

to have 3 optional command line argument in any order (username,the server host num,the server port num ).I write it this way but it won't work.could somebody please help me to figure out what to do.thanks

  if (argc<1 || argc>4)
    fprintf(stderr, "usage error: incorrect number of arguments\n");
else 
    for(int i=1;i<=argc;i++)
    {
        if (strcmp( argv[i],"-u"==0 )
             username=argv[i];
        if(strcmp(argv[i],"-p"==0)
            port=atoi(argv[i]);
        if (strcmp(avrgv[i],"-h"==0)
            host=(argv[i]);

Upvotes: 0

Views: 1105

Answers (2)

Summer_More_More_Tea
Summer_More_More_Tea

Reputation: 13356

You should increase the index to get value of the argument bypassing the options. e.g. modify your code like this.

   if (argc<1 || argc>4)
        fprintf(stderr, "usage: %s -u username\n", argv[0]);
    else 
        for(int i=1;i<=argc;i += 2)
        {
            if (strcmp( argv[i],"-u")==0 )
                 username=argv[i + 1];

Also you'd better define username as a char array and copy argument value into it, so you can modify it directly, like this:

char username[NAME_LEN + 1];                            // +1 for tailing '\0'
strncpy(username, argv[i + 1], NAME_LEN);

Upvotes: 0

user229044
user229044

Reputation: 239311

Use getopt, it's purpose-built for handling command line arguments in a consistent way, something which is notoriously difficult to do correctly.

Upvotes: 1

Related Questions