简体   繁体   中英

Command Line Argument C

I need help to display name to command line like this (I don't know how to explain) in C

$:Enter your name: Test
$:Test>

But when you continue press enter it still showing Test>

$:Test>
$:Test>

So how do we get argv[0] and do something like this (Sorry that I cannot explain probably)

Thank you

command line arguments are stored in char **argv, and there are argc of them.

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)

Whenever possible, you should use getopt() so that the order of your parameters doesn't matter. 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. 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.

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.

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.

If you had rather shell-like program in mind, maybe the following couldbe of use:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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