如何通过终端将值传递给程序功能

时间:2018-04-11 21:30:58

标签: c function terminal

#include <stdio.h>
void fun_one(int a,int b);
void fun_two(int a,int b);
int main()
{
    printf("Result=");
    return 0;
}

void fun_one(int a,int b){
    printf("%d\n",a+b);
}
void fun_two(int a,int b){
    printf("%d\n",a*b);
}

我以这种方式编译和运行程序:

cc exec.c -o exec

./ exec&lt; fun_two 3 4

但它没有返回我的预期。命令中是否有错误?

输出: 结果=

1 个答案:

答案 0 :(得分:1)

此代码编辑显示如何使用您输入的两个数字的功能2。

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


void fun_one(int a,int b);
void fun_two(int a,int b);
int main(int, char **);


int main(int argc, char ** argv)
{
    int a,b;
    a= atoi(argv[1]);
    b=atoi(argv[2]);
    printf("Result=");fun_two(a,b); // similar to what you want from comments

    //using both functions
    printf("a+b=");fun_one(a,b); 
    printf("a*b=");fun_two(a,b); 
    return 0;
}

void fun_one(int a,int b){
    printf("%d\n",a+b);
    return;
}
void fun_two(int a,int b){
    printf("%d\n",a*b);
    return;
}

我修改了你的代码,以便用

编译它
gcc -o exec exec.c 

您可以使用

运行它
./exec 4 3

获取所需的输出 - 请注意,我希望使用cc编译将提供完全相同的输出,但我无法测试它。

我所做的是更改了main的定义,以便它可以接受您调用时的输入。额外的位被放入字符串中。

函数atoi ascii 字符串转换为 整数数字,以便您在命令行中输入的数字可以是处理为数字而不是字符串。

请注意,此代码相当脆弱,可能会分段。故障。如果在调用程序后没有输入两个数字,结果将无法预测。你可以通过检查argc的值来确保它更可靠 - 当你输入命令时通过检查atoi工作时输入的东西的数量,但这会使代码更长,我认为更重要的是看到做你想做的事的方式。

下面是一个更通用的代码,它允许您选择要在代码中运行的功能....

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


void fun_one(int a,int b);
void fun_two(int a,int b);
int main(int, char **);


int main(int argc, char ** argv)
{
    int a,b;
    a= atoi(argv[2]);
    b=atoi(argv[3]);

    if (!strcmp("fun_one",argv[1])) 
    { 
         printf("Result=");fun_one(a,b); 
    }
    else if (!strcmp("fun_two",argv[1])) 
    { 
         printf("Result=");fun_two(a,b); 
    }
    else printf("Didn't understand function you requested.  \n\n");

    return 0;
}

void fun_one(int a,int b){
    printf("%d\n",a+b);
    return;
}
void fun_two(int a,int b){
    printf("%d\n",a*b);
    return;
}

该功能现在为以下输入提供以下输出

./exec fun_three 3 4
Didn't understand function you requested.  

./exec fun_one 3 4
Result=7
./exec fun_two 3 4
Result=12

所以现在使用上面的代码,在命令之后输入三个东西 - 你想要的功能,然后输入两个数字 - 如果没有识别功能,则会出现错误信息。

函数strcmp比较两个字符串,如果它们相同则返回零。零在逻辑中等于false,因此!符号用作not,它将0转换为1,将数字不等于0转换为0。结果是,如果两个字符串相同,则逻辑测试将为真。