📜  C中的命令行参数示例

📅  最后修改于: 2021-05-28 03:06:59             🧑  作者: Mango

先决条件:Command_line_argument。

问题是使用命令行参数在三个整数中找到最大的整数。

笔记:

  • 在操作系统的命令行外壳程序中,在程序名称之后给出命令行参数。为了传递命令行参数,我们通常使用两个参数定义main():第一个参数是命令行参数的数量,第二个是命令行参数的列表。
    int main(int argc, char *argv[]) { /* ... */ }
  • atoi –用于将字符串数字转换为整数

    例子:

    Input  : filename 8 9 45
    Output : 45 is largest
    
    Input  : filename 8 9 9
    Output : Two equal number entered
    
    Input  : filename 8 -9 9
    Output : negative number entered
    

    在程序执行期间,我们将三个整数与程序的文件名一起传递,然后我们将在三个整数中找到最大的数字。
    方法 :

    1. 如果两个条件中的任何一个满足,程序将“返回1”:
      • 如果两个数字相同,则打印“输入两个相等的数字”语句。
      • 如果有任何负数,则打印“输入负数”。
    2. 如果输入了三个不同的整数,则否则返回“ 0”。

    为了更好地理解,请在您的linux机器上运行此代码。

    // C program for finding the largest integer
    // among three numbers using command line arguments
    #include
      
    // Taking argument as command line
    int main(int argc, char *argv[]) 
    {
        int a, b, c;
      
        // Checking if number of argument is
        // equal to 4 or not.
        if (argc < 4 || argc > 5) 
        {
            printf("enter 4 arguments only eg.\"filename arg1 arg2 arg3!!\"");
            return 0;
        }
      
        // Converting string type to integer type
        // using function "atoi( argument)" 
        a = atoi(argv[1]); 
        b = atoi(argv[2]);
        c = atoi(argv[3]);
      
        // Checking if all the numbers are positive of not
        if (a < 0 || b < 0 || c < 0) 
        {
            printf("enter only positive values in arguments !!");
            return 1;
        }
      
        // Checking if all the numbers are different or not
        if (!(a != b && b != c && a != c)) 
        {
            printf("please enter three different value ");
            return 1;
        }
        else
        {
            // Checking condition for "a" to be largest
            if (a > b && a > c)             
                printf("%d is largest", a);
      
            // Checking condition for "b" to be largest    
            else if (b > c && b > a) 
                printf ("%d is largest", b);
      
            // Checking condition for "c" to be largest..
            else if (c > a && c > b) 
                printf("%d is largest ",c);
        }
        return 0;
    }
    

    输出 :


    想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。