foo
foo

Reputation: 2311

Reading command line arguments in a C program

What this does is converts the argument ./a.out -b 101 into a decimal 5 though what I am trying to do is only covert the 101 into a binary number if I give it the argument -b

#include <stdio.h>
void main(int argc, char *argv[])
{
  if ((argc == 3) && (argv[2] == "-b") ) //here lies the problem
  {
    int n = 0;
    char *c_pt = argv[2];

    printf("argv[1]: %s\n", argv[1]);
    while (*c_pt)
    {
      if (*c_pt < '0' || *c_pt > '1')
      {
        break;
      }
      n = n * 2 + *c_pt - '0';
      c_pt++;
    }
    printf("%d\n", n);

  }
}

Upvotes: 0

Views: 986

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753705

Argument indexes count from 0 with the name of the program. argv[1] contains the string "-b", while argv[2] contains the string "101".

Additionally, you need to #include <string.h> and use strcmp() to compare strings.

Internally, the number will be binary regardless of how you convert it. However, there isn't an easy way of printing a binary number in C. You can use strtol() (from <stdlib.h>), or one of its relatives, to convert the string as a binary value. You should probably use that to convert the string into a value (though, in general, you need to be rather careful detecting the error conditions from strtol(); it is subtle with its returns).

7.20.1.4 The strtol, strtoll, strtoul, and strtoull functions

long strtol(const char * restrict nptr, char ** restrict endptr, int base);

¶7 If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

Returns

¶8 The strtol, strtoll, strtoul, and strtoull functions return the converted value, if any. If no conversion could be performed, zero is returned. If the correct value is outside the range of representable values, LONG_MIN, LONG_MAX, LLONG_MIN, LLONG_MAX, ULONG_MAX, or ULLONG_MAX is returned (according to the return type and sign of the value, if any), and the value of the macro ERANGE is stored in errno.

You would want to ensure that all the non-blank characters were converted, amongst other things.

Upvotes: 2

sehe
sehe

Reputation: 392979

#include <stdio.h>

void main(int argc, char *argv[])
{
    if ((argc == 3) && (0 == strcmp(argv[1], "-b")) ) //here lies the problem
    {
        int n = 0;
        char *c_pt = argv[2];

        printf("argv[2]: %s\n", argv[2]);
        while (*c_pt)
        {
            if (*c_pt < '0' || *c_pt > '1')
            {
                break;
            }
            n = n * 2 + *c_pt - '0';
            c_pt++;
        }
        printf("%d\n", n);

    }
}

Allthough my version would rather use

char* end;
printf("%li\n", strtol(argv[2], &end, 2));

Upvotes: 1

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

In C you need to call strcmp(3) to compare strings.

Upvotes: 3

Related Questions