2014-09-29 84 views
0

我想這個程序改爲從命令行讀取指令。它是八進制數字轉換器 - >二進制和二進制 - >八進制。在運行要轉換的內容之前,我不能告訴它嗎?例如./conv八進制二進制11會產生八進制3.我已經運行過linux程序,我使用./script輸入輸出。C程序從命令行讀取輸入

#include <stdio.h> 
#include <math.h> 
int binary_octal(int n); 
int octal_binary(int n); 
int main() 
{ 
    int n; 
    char c; 
    printf("Instructions:\n"); 
    printf("Enter alphabet 'o' to convert binary to octal.\n"); 
    printf("2. Enter alphabet 'b' to convert octal to binary.\n"); 
    scanf("%c",&c); 
    if (c=='o' || c=='O') 
    { 
     printf("Enter a binary number: "); 
     scanf("%d",&n); 
     printf("%d in binary = %d in octal", n, binary_octal(n)); 
    } 
    if (c=='b' || c=='B') 
    { 
     printf("Enter a octal number: "); 
     scanf("%d",&n); 
     printf("%d in octal = %d in binary",n, octal_binary(n)); 
    } 
    return 0; 
} 
int binary_octal(int n) /* Function to convert binary to octal. */ 
{ 
    int octal=0, decimal=0, i=0; 
    while(n!=0) 
    { 
     decimal+=(n%10)*pow(2,i); 
     ++i; 
     n/=10; 
    } 

/*At this point, the decimal variable contains corresponding decimal value of binary number. */ 

    i=1; 
    while (decimal!=0) 
    { 
     octal+=(decimal%8)*i; 
     decimal/=8; 
     i*=10; 
    } 
    return octal; 
} 
int octal_binary(int n) /* Function to convert octal to binary.*/ 
{ 
    int decimal=0, binary=0, i=0; 
    while (n!=0) 
    { 
     decimal+=(n%10)*pow(8,i); 
     ++i; 
     n/=10; 
    } 
/* At this point, the decimal variable contains corresponding decimal value of that octal number. */ 
    i=1; 
    while(decimal!=0) 
    { 
     binary+=(decimal%2)*i; 
     decimal/=2; 
     i*=10; 
    } 
    return binary; 
} 

回答

3

命令行選項通過argcargv傳遞給main

int main(int argc, char** argv) 
{ 
    for(int i=0; i<argc; ++i) 
    { 
     printf("Option %d is %s\n", i, argv[i]); 
    } 
} 

試着用各種命令行參數運行這個迷你程序,你會很快找到它!

+2

'argv [0]'通常是命令行中鍵入的程序的名稱。 – pts 2014-09-29 21:07:31