Optional read from STDIN in C
Posted
by Yuval A
on Stack Overflow
See other posts from Stack Overflow
or by Yuval A
Published on 2010-04-18T19:14:18Z
Indexed on
2010/04/18
19:23 UTC
Read the original article
Hit count: 281
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.
© Stack Overflow or respective owner