c - 如何将 argv[] 的几个字符传递给 C 中的函数?

标签 c

我想将 argv[] 的几个字符传递给函数,然后返回一个值。
例如:

int main(int argc, char *argv[]) {
    int n1, value;
    for (i = 1; i <= n1; i++) {
        value = Convert(argv[]);
        printf("%d\n", value);
    }
}

float Convert(*argv[]) {
    int value;

    switch(*argv[]){
        case 'ABC': value = 1; break;
        case 'DEF': value = 2; break;
        case 'GHI': value = 3; break;
        default: value = 0; break;
    }
    return value;
}

我知道存在语法错误,但我不知道如何纠正它们。

希望你明白我的意思,抱歉我的英语不好。

最佳答案

有几个错误,请看原代码的注释:

int main(int argc, char *argv[]){
    int n1, value;
    for (i = 1; i <= n1; i++) {
        // you cannot pass it like that, if you want to pass the whole argv, it should be
        // value = Convert(argv);
        // If you want to pass one argument at a time it should be
        // value = Convert(argv[i]);
        value = Convert(argv[]);
        printf("%d\n", value);
    }
}

//If you want to pass one argument each time, the declaration should be
// int Convert(char * argv)
// Also note that you expect an int in return, not a float
float Convert(*argv[]){
    int value;

// you cannot switch on strings, only on integer types, so you need to perform if/else checks:
/*
if (strcmp(argv, "ABC") == 0) {
    value = 1;
}
else if (strcmp(argv, "DEF") == 0) {
    value = 2;
}
else if (strcmp(argv, "GHI") == 0) {
    value = 3;
}
else {
    value = 0;
}

*/
    switch(*argv[]){
    case 'ABC': value = 1;break;
    case 'DEF': value = 2;break;
    case 'GHI': value = 3;break;
    default: value = 0;break;
    }
    return value;
}

关于c - 如何将 argv[] 的几个字符传递给 C 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9034178/

相关文章:

c++ - 如何在 Linux 上挂接 send()/recv() 函数?

C语言——矩阵乘法bug

c - 与 GHC 链接

c - 使用c中的结构访问结构成员数组

c - 制作空白输出文件的程序,C

c - *((int *) arg) 是做什么的?

c - 尝试计算C中字符串中有多少个字符

c - 深栈展开

c - C 中的静态结构声明

c - POSIX 线程,独特的执行