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.
a source to share
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 {
// :-/
}
}
a source to share
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.
a source to share