Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally execute scanf function?

Tags:

c

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?

like image 782
flylib Avatar asked Apr 29 '26 13:04

flylib


2 Answers

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);
    ...
}
like image 125
zakinster Avatar answered May 02 '26 03:05

zakinster


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.

like image 31
Lundin Avatar answered May 02 '26 03:05

Lundin