2013-02-08 130 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也需要一個字符串,與上面相同。