简体   繁体   English

命令行参数C

[英]Command Line Argument C

I need help to display name to command line like this (I don't know how to explain) in C 我需要帮助以C语言在命令行中显示名称(不知道如何解释)

$:Enter your name: Test
$:Test>

But when you continue press enter it still showing Test> 但是当您继续按Enter时,它仍然显示Test>

$:Test>
$:Test>

So how do we get argv[0] and do something like this (Sorry that I cannot explain probably) 因此,我们如何获得argv [0]并执行类似的操作(对不起,我可能无法解释)

Thank you 谢谢

command line arguments are stored in char **argv, and there are argc of them. 命令行参数存储在char ** argv中,并且其中有argc。

int main(int argc, char **argv)
{
    int i=0;
    for(i=0; i< argc; i++)
       printf("argument number %d = %s\n", i, argv[i]);
    return 0;
}

argv[0] is the name of the program being executed, so argc is always at least == 1 ( or more) argv [0]是正在执行的程序的名称,因此argc始终至少为== 1(或更大)

Whenever possible, you should use getopt() so that the order of your parameters doesn't matter. 只要有可能,就应该使用getopt(),以便参数顺序无关紧要。 For example, suppose you wanted to take an integer parameter for the size, an integer for the mode of execution, and a toggle to indicate whether to run in "quiet mode" or not. 例如,假设您要为该大小采用一个整数参数,为执行模式采用一个整数,并使用一个切换来指示是否以“安静模式”运行。 Further suppose that "-h" should print help and exit. 进一步假设“ -h”应打印帮助并退出。 Code like this will do the trick. 这样的代码可以解决问题。 The "s:m:hq" string indicates that "-s" and "-m" provide parameters, but the other flags don't. “ s:m:hq”字符串表示“ -s”和“ -m”提供参数,而其他标志则不提供。

int main() {
  // parse the command-line options
  int opt;
  int size = DEFAULT_SIZE, mode = DEFAULT_MODE, quiet = 0;
  while ((opt = getopt(argc, argv, "s:m:hq")) != -1) {
    switch (opt) {
      case 's': size  = atoi(optarg); break;
      case 'm': mode  = atoi(optarg); break;
      case 'q': quiet = 1;            break;
      case 'h': usage(); return 0;
    }
  }
  // rest of code goes here
}

Of course, you should add error checking in case optarg is null. 当然,如果optarg为null,则应该添加错误检查。

Also, if you're using C++, "string(optarg)" is an appropriate way for your case statement to set a std::string to hold a value that is stored as a char* in argv. 另外,如果您使用的是C ++,则“ string(optarg)”是case语句设置std :: string的合适方式,以保存以char *形式存储在argv中的值。

If you had rather shell-like program in mind, maybe the following couldbe of use: 如果您想到的是类似shell的程序,则可以使用以下程序:

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

#define BUFSIZE 64

int main() {
  char prompt[BUFSIZE];
  char command[BUFSIZE];
  char *prefix = "$:";
  char *suffix = ">";

  printf("%s%s%s", prefix, "Enter your name:", suffix);
  fgets(prompt, BUFSIZE, stdin);
  prompt[strlen(prompt)-1] = '\0'; // get rid of the \n

  while (true) {
    printf("%s%s%s", prefix, prompt, suffix);
    fgets(command, BUFSIZE, stdin);
    if (strncmp(command,"Quit",4) == 0)
      break;
  }

  return 0;
}

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

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