Reputation: 83
I need to create some form of input where the user can type in various instructions. It is optional whether they append a value such as: 'ADD1'. Add is the instruction, 1 is the value. If no value is appended instructions will be carried out where no value is required such as 'END' for looping. Let's say the user does not enter a value, how do i make this possible so that 'val' is optional? If no value is appended scanf should just attatch the string input to 'instr' and ignore 'val'.
Sample:
Scanf("%s %d", instr, val);
Upvotes: 2
Views: 967
Reputation: 726539
Generally, the approach to problems like that is to use scanf
to get in the whole string, and then parse it yourself when it is in memory:
char cmdline[100];
scanf("%99s", cmdline);
if (strstr(cmdline, "ADD") == cmdline) {
... Get an int from cmdline buffer starting at position 3
} else if (strstr(cmdline, "END") == cmdline) {
... Don't get anything
}
Upvotes: 3