user2054534 user2054534 -4 years ago 77
C Question

Command line parameter inter c

I want to make this program do the printing in

main()
only there are no command line arguments.
If there are command line arguments (which should just be one integer), it should run the function
bitcount()
.

How do I go about doing this? If there are no command line arguments I am not sure how this will work properly.

How would I check if the user put in a command line argument? And if they did, run
bitCount()
and not the
main()
. However if they do not put any command line integer argument, then it would just run main.

e.g
./bitCount 50
should call the
bitCount
function
but
./bitCount
should just run the
main


Here's what I have so far:

#include <stdio.h>
#include <stdlib.h>

int bitCount (unsigned int n);
int main ( int argc, char** argv) {

printf(argv);
int a=atoi(argv);

// int a = atoi(argv[1]);

printf ("# 1-bits in base 2 representation of %u = %d, should be 0\n",
0, bitCount (0));
printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
1, bitCount (1));
printf ("# 1-bits in base 2 representation of %u = %d, should be 16\n",
2863311530u, bitCount (2863311530u));
printf ("# 1-bits in base 2 representation of %u = %d, should be 1\n",
536870912, bitCount (536870912));
printf ("# 1-bits in base 2 representation of %u = %d, should be 32\n",
4294967295u, bitCount (4294967295u));
return 0;
}

int bitCount (unsigned int n) {
//stuff here
}

Answer Source

argv is an array of strings that contains the program name followed by all arguments. argc is the size of the argv array. argc is always at least 1 for the program name.

If there was a paramter argc will be > 1.

So,

if (argc > 1)
{
    /* for simplicity ignore if more than one parameter passed, just use first */
    bitCount(atoi(argv[1]));
}
else
{
    /* do stuff in main */
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download