简体   繁体   English

实施命令行参数

[英]Implementing a command-line argument

I have to implement the main function with the following signature: 我必须使用以下签名来实现主要功能:

    int main(int argc, char *argv[])

What is a command-line argument and why don't I need test cases for it? 什么是命令行参数,为什么我不需要测试用例? And what do they mean by "signature"? 它们的“签名”是什么意思? Is it just the function prototype? 仅仅是功能原型吗?

And I will definitely edit this question to include my attempt at the solution once I get these things clarified. 一旦我弄清楚了这些内容,我肯定会编辑此问题,以包括我对解决方案的尝试。

I'm confused on what this program essentially does, I can see it returns an integer value, but what does that integer value represent? 我对该程序的本质感到困惑,我可以看到它返回一个整数值,但是该整数值代表什么? Also, how would I return an integer value with the arguments specified in the argument list? 另外,我将如何使用参数列表中指定的参数返回整数值? What do they mean? 他们的意思是什么? Thanks for the help! 谢谢您的帮助!

While this is a terrible question that shows little effort, I feel obligated to help ease your confusion. 虽然这是一个令人费解的问题,但付出了很少的努力,但我有义务帮助您减轻混乱。

Here's a program which prints out it's name ( argv[0] ), and requires at least one argument. 这是一个打印出其名称( argv[0] )并需要至少一个参数的程序。 If it isn't given at least one argument, it returns 1 to indicate failure. 如果未至少提供一个参数,则返回1表示失败。 Otherwise, it prints out its arguments and returns 0 to indicate success (to the shell, or whoever started it). 否则,它将输出其参数,并返回0表示成功(对于Shell或启动它的任何人)。

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("Hello World, my name is \"%s\" \n", argv[0]);

    if (argc < 2) {
        printf("I require at least 1 argument! Exiting!\n");
        return 1;  // Indicate failure.
    }


    printf("I was given %d command-line arguments:\n", argc-1);
    for (i=1; i<argc; i++) {
        printf("  [%d] %s\n", i, argv[i]);
    }

    return 0;    // Indicate success
} 

Compile and run that program, things should become more clear. 编译并运行该程序,情况应该变得更加清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM