I want the user to be able to input two types of input like: "C[some size_t]" and "O[some memory address]" and depending on whether it's a C or O at the beginning, I'll call different functions. I also want to be able to take in an unknown number of those inputs and in any order.
My way of going around it was something like this:
int main()
{
// variables
while (1) { // Infinite loop to take in multiple unknown amount of inputs?
while (fgets(input, BUFFER_SIZE, stdin)) {
if (sscanf(input, "%c%zu", &branch, &num) == 2) {
if (strcmp(&branch, "C")
// function call
} else if (sscanf(input, "%c%c", &branch, (char *)addr) == 2) {
if (strcmp(&branch, "O")
// function call
}
}
}
return 0;
}
I understand why it's not working of course and I know my not-solution is wrong but I have no idea how else to go about this. The code takes in the first input and just hangs and if I start with an input beginning with O, it'll go into the first if
statement when it's not supposed to. I'm also not sure if my while(1)
loop is the correct way to deal with multiple user inputs.
CodePudding user response:
You try to read the branch
char and the respective argument in one single go – however the argument differs in both cases. So you need first to read the character, then decide and only then scan the argument – as soon as you know what to scan at all and thus are able to select the appropriate format string.
As you just read in any character you could do so a bit simpler with getc
, by the way:
char branch = getc(); // instead of `if(scanf("%c", &branch) == 1)`
// note: would have been one single scan (branch) only!
if(branch == 'C')
{
// scan num
}
else if(branch == 'O')
{
// scan addr
}
else
{
// error handling
}
or alternatively (I personally would prefer)
char branch = getc();
switch(branch)
{
case 'C':
// scan num
break;
case 'O':
// scan addr
break;
default:
// error handling
break;
}
Note that strcmp
requires null-terminated strings (char arrays) and cannot be used for comparing single characters – these need to be compared via equality operator, see above.