Reputation: 45
is there a way to have optional input variables in scanf ?
I have a program that scans input until EOF. That input can look like this:
+ 10 20 30
- 10 20 30
? 10
When I type (or read from a file) + or - it is always followed by three numbers but when I type in ? it is only followed by one number (always).
My current code looks like this:
#include <stdio.h>
#include <stdlib.h>
int main(){
char action;
int dc1,dc2,cable;
while(scanf(" %c %d %d %d",&action,&dc1,&dc2,&cable)!=EOF){
if((dc1==dc2)||(cable<1)||(dc1>999)||(dc2>999)||(dc1<0)||(dc2<0)){
printf("Wrong input.\n");
return 0;
}
else{
if(action=='+'){
/*code*/
}
else if(action=='-'){
/*code*/
}
else if(action=='?'){
/*code*/
}
else{
printf("Wrong input.\n");
return 0;
}
}
}
return 0;
}
Right now it requires me to type in three numbers all the time, even if I want to type in the "?" action.
Is there a way to make some of the variables in scanf optional so the input "? 10" would also be valid.
PS.
I have stripped the code so it is not too long. I hope I have included everything that is necessary.
I would also appreciate if I didn't have to rework the code too much because it is basically done, everything works like it needs to. This is the only thing that is stopping me from turning in my code.
PPS. This is for a homework.
Upvotes: 2
Views: 3855
Reputation: 30926
As mentioned in comment this can be easily checked with sscanf()
and fgets
.
We are using the fgets
to read a line and then pass it to the parser function. That function tries to parse the line. sscanf
returns the successful number of parameters passed. Based on that count
we are deciding which input it is.
This code is just a starting point for how to start. It avoids the lots of error checking and concentrates on the technique as discussed above by Jonathan Leffler.
Code example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 256
void add (int b,int c,int d){
printf("%d+%d+%d=%d\n",b,c,d,b+c+d);
}
void sub (int b,int c,int d){
printf("%d-%d-%d=%d\n",b,c,d,b-c-d);
}
void query (int a){
printf("?%d\n",a);
}
void parseAndProcess(const char *buf){
char a;
int b, c, d;
size_t ct;
ct = sscanf(buf,"%c%d%d%d",&a,&b,&c,&d);
if( ct <= 1){
//error
}
else if( ct==2 ) {
if( a == '?'){
query(b);
}
else{
//error
}
}
else if( ct == 3){
// error
}
else if( ct == 4){
if( a == '+') add(b,c,d);
else if( a == '-') sub(b,c,d);
else{
//error
}
}
else{
// error
}
}
int main(void){
char buf[BUFFSIZE];
while(fgets(buf,BUFFSIZE,stdin)){
parseAndProcess(buf);
}
return EXIT_SUCCESS;
}
Here add
,sub
methods are to be implemented for actual code. A demo implementation is shown here above. For example here in add
,sub
no overflow checking is there.
Upvotes: 2