So I have a program where I need to take an initial command from a user using the scanf function, the problem is it could just be one string command, one string command and a string argument, one string command and a int argument or one string command and two int arguments
so I need to somehow create one scanf function that is able to handle all of these because I don't know which one will be picked first
so the code I made to handle all edge cases is
scanf("%s", c);
scanf("%s%s", c, s;
scanf("%s%d", c, &i);
scanf("%s%d%d", c, &i, &i2);
and examples of possible commands that could be typed by end user
print
insert Hello
del 4
pick 2 5
but this won't work
So is there a way to make a scanf function that executes conditionally?
You could read only the first word and then determine what you need to read next :
char command[32];
scanf("%s", command);
if(strncmp(command, "print", 32) == 0) {
...
}
else if(strncmp(command, "insert", 32) == 0) {
char string[32];
scanf("%s", string);
...
}
else if(strncmp(command, "del", 32) == 0) {
int i;
scanf("%d", &i);
...
}
else if(strncmp(command, "pick", 32) == 0) {
int i, j;
scanf("%d %d", &i, &j);
...
}
Read the whole line, preferably with a safe function like fgets, then parse the resulting string to determine if the user wrote a valid command. Conditional execution can then be achieved using the if statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With