1. 程式人生 > >命令列引數中如何輸入星號

命令列引數中如何輸入星號

開發十年,就只剩下這套架構體系了! >>>   

教小朋友寫程式。設計一個:

./calc + 3 4               程式輸出 3+4 = 7

支援四中運算,+,-,*,/

但輸入:./calc * 5 6

Usage: hello op a b, op:[+,-,*,/]
argc:6
./calc,a.txt,calc,hello.c,5,6,

並不是5個引數,而是六個引數。 * 被擴充套件成a.txt, calc,hello.c。這個Shell設計,*代表當前目錄下的任何檔案。

要想正確呼叫,得寫做 ./calc '*' 5 6

 

 

 

 

 

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


int add(int a, int b) {
    return a + b;
}

int sub(int a, int b) {
    return a - b;
}

int mul(int a, int b) {
    return a * b;
}

int divi(int a, int b) {
    return a / b;
}


int main(int argc, char* argv[]) {
    int a,b,c;
    const char* op;

    printf("Hello,world\n");
    if (argc != 4) {
        int i;
        printf("Usage: hello op a b, op:[+,-,*,/]\n");
        printf("argc:%d\n",argc);    
        for (i = 0; i < argc; i++) {
            printf("%s\n", argv[i]);
        }

        
        return 0;
    }

    op = argv[1];
    a = atoi(argv[2]);
    b = atoi(argv[3]);
    if (strcmp(op,"+") == 0) {
        c = add(a,b);
        printf("%d+%d=%d\n", a, b, c);
    } else if (strcmp(op, "-") == 0) {
        c = sub(a,b);
        printf("%d-%d=%d\n", a, b, c);
    } else if (strcmp(op, "x") == 0) {
        c = mul(a,b);
        printf("%d*%d=%d\n", a, b, c);
    } else if (strcmp(op, "/") == 0) {
        c = divi(a,b);
        printf("%d/%d=%d\n", a, b, c);
    }
        
    return 0;