2013-02-08 132 views
0

我想让这个程序在main()中执行打印,只有没有命令行参数。 如果有命令行参数(应该只是一个整数),它应该运行功能bitcount()命令行参数c

我该如何去做这件事?如果没有命令行参数,我不确定这将如何正常工作。

如何检查用户是否放入命令行参数?如果他们这样做,运行bitCount()而不是main()。但是,如果他们不放置任何命令行整数参数,那么它只会运行main。

./bitCount 50应该调用bitCount功能 但./bitCount应该只是运行main

这是我到目前为止有:

#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 
    } 
+0

的argc是参数的个数,和argv是参数数组。所以,只需检查'argc> 1'(第一个参数是文件名),然后使用'argv [1]'访问值(第一参数)。 – Supericy 2013-02-08 22:08:28

+0

真的吗?你说你有**绝对不知道**如何做到这一点?这不可能。 – 2013-02-08 22:08:40

回答

0

argv是一个字符串数组,其中包含程序名称后跟所有参数。 argc是argv数组的大小。对于程序名称,argc总是至少为1。

如果有一个放慢参数的argc将> 1.

所以,

if (argc > 1) 
{ 
    /* for simplicity ignore if more than one parameter passed, just use first */ 
    bitCount(atoi(argv[1])); 
} 
else 
{ 
    /* do stuff in main */ 
} 
0

int argc包含的参数在命令行中的数字,其中可执行文件的名称是argv [0]。因此,argc < 2表示没有给出命令行参数。在没有命令行参数的情况下,我不明白你想要什么或不想运行,但它应该在if (argc < 2)的后面。

在你的示例代码,你在介意做一些非常奇怪的事情,这一点:

printf(argv); 

将以argv是一个char **,或char *数组,永远不会产生任何有用的东西。更糟糕的是,因为printf希望格式化字符串作为它的第一个参数,所以上面的代码会导致各种奇怪的事情。

​​

相同。 atoi也需要一个字符串,与上面相同。