简体   繁体   中英

Optional read from STDIN in C

My application is basically a shell which expects an input of type cmd [x] , where cmd is constant and x is optional. So cmd 1 is legal as well as cmd by itself - then I assume a default parameter for x .

I am doing this:

char cmd[64];
scanf("%s", cmd);
int arg;
scanf("%d", &arg); // but this should be optional

How can I read the integer parameter, and set it to a default if none is currently available in the prompt? I do not want the prompt to wait for additional input if it was not given in the original command.

I tried several versions using fgetc() and getchar() and comparing them to EOF but to no avail. Each version I tried ends up waiting on that optional integer parameter.

The easy way:

   char b[73]; //powers of 2 magic is evil.
    if(fgets(b,sizeof b,stdin) != NULL) {
      char cmd[59]; //59, no command will ever be > 58. Ever I say.
      int arg;
      if(sscanf(b,"%58s %d",cmd,&arg) == 2) {
         //handle cmd and arg
      } else if(sscanf(b,"%58s",cmd) == 1) {
         //handle cmd only
      } else {
       // :-/
      }
    }

Simple answer, you can't. The C runtime takes input from the OS, but doesn't control it. To do something like this you will need to interact directly with the OS using platform specific APIs.

Are you reading line-by-line? Can't you just read the whole command until you reach a "\\n" (newline)? If you get two tokens before the newline, it is a command and the argument; if you read only one, it is the command only and you set the second argument to the default.

Here's a program that works (sorry my previous answer was made in haste).

int main(){
    char cmd[100], line[100];
    int man = 0;
    printf("OK: ");
    fgets(line, 100, stdin);
    int num = sscanf(line,"%s %d",cmd,&man);
    if (num==1)printf("one! %s %d\n", cmd, man);
    else if (num==2)printf("two! %s %d\n", cmd, man);
}

fgets reads the line (with bounds checking), and sscanf will assess whether one or two tokens were entered.

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