Additional reading from STDIN in C

My application is basically a wrapper that expects a type input cmd [x]

where cmd

is a constant and x

is optional. Therefore cmd 1

is legal as well as cmd

on its own - then I accept the default parameter for x

.

I'm doing it:

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 as default if the prompt is not currently present? I don't want the prompt to wait for additional input unless it was specified in the original command.

I have tried several versions with fgetc()

and getchar()

and compared with EOF

, to no avail. Every version I've tried ends up waiting for this optional integer parameter.

+2


a source to share


4 answers


Simple 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 {
       // :-/
      }
    }

      

+3


a source


Simple answer, you can't. The C runtime accepts input from the OS, but does not control it. To do something like this, you would need to interact directly with the OS using the platform APIs.



+2


a source


Are you reading line by line? Can't you just read the entire command until you reach "\ n" (newline)? If you get two tokens before a newline, it's a command and an argument; if you only read one, it is only a command and you are setting the second argument as default.

+1


a source


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

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 a line (with bounds checking), and sscanf will detect if one or two tokens have been entered.

0


a source







All Articles